现在的位置: 首页 > 综合 > 正文

NSURLConnection

2013年09月15日 ⁄ 综合 ⁄ 共 6137字 ⁄ 字号 评论关闭

NSURLRequest提供一种快捷的方式来下载url对应的内容,提供了创建、取消接口。并且支持delegate的一系列回调方法,用于控制链接的各个方面。这些方法分为五类:URL loading, cache management, authentication and credentials, cookie storage, and protocol support.

 

使用NSURLRequest建立url请求,需要提供delegate中最起码的以下几个方法 connection:didReceiveResponse:connection:didReceiveData:,connection:didFailWithError: and connectionDidFinishLoading:.

1.初始化url链接,制定cache缓冲策略,有效等待时间,如果正常建立链接 则返回NSURLConnection实例,否则返回nil.

从调用initWithRequest,链接正式建立,在收到 connectionDidFinishLoading: or connection:didFailWithError消息之前 都可以通过调用cancel取消链接。

 

Listing 1  Creating a connection using NSURLConnection

// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]
                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                    timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
    // Create the NSMutableData to hold the received data.
    // receivedData is an instance variable declared elsewhere.
    receivedData = [[NSMutableData data] retain];
} else {
    // Inform the user that the connection failed.

2.当服务器准备好足够的信息时 即调用 connection:didReceiveResponse: 来返回消息,有可能会多次调用,比如由于服务器的 重定向或者有很多个MIME部分。

Listing 2  Example connection:didReceiveResponse: implementation

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // This method is called when the server has determined that it
    // has enough information to create the NSURLResponse.
 
    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
 
    // receivedData is an instance variable declared elsewhere.
    [receivedData setLength:0];
}

3.当收到数据时,delegate周期性的发送

connection:didReceiveData: 消息。

Listing 3  Example connection:didReceiveData: implementation

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere.
    [receivedData appendData:data];
}

You can also use the connection:didReceiveData: method to provide an indication of the connection’s progress to the user.

可以在这里更新进度条。

4.如果在链接过程中 出现错误,则会发送 connection:didFailWithError:消息,NSError 对象作为参数用来说明具体错误内容。发生错误的URL可以通过

[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);得到。

Listing 4  Example connectionDidFailWithError: implementation

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
    // release the connection, and the data object
    [connection release];
    // receivedData is declared as a method instance elsewhere
    [receivedData release];
 
    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
5.若下载数据正常完成,则会收到

 connectionDidFinishLoading: message ,这是最后收到的消息,之后将不会收到消息。


Listing 5  Example connectionDidFinishLoading: implementation

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
 
    // release the connection, and the data object
    [connection release];
    [receivedData release];

 

}

 

注:一步只能收到connectionDidFinishLoading和didFailWithError消息中的一个,作为最后收到的消息。


Controlling Response Caching

By default the data for a connection is cached according to the support provided by the NSURLProtocol subclass that handles the request. An NSURLConnection delegate can further refine that behavior by implementingconnection:willCacheResponse:.

This delegate method can examine the provided NSCachedURLResponse object and change how the response is cached, for example restricting its storage to memory only or preventing it from being cached altogether. It is also possible to insert objects in an NSCachedURLResponse’s user info dictionary, causing them to be stored in the cache as part of the response.

Note: The delegate receives connection:willCacheResponse: messages only for protocols that support caching.

 

The example in Listing 6 prevents the caching of https responses. It also adds the current date to the user info dictionary for responses that are cached.

Listing 6  Example connection:withCacheResponse: implementation

-(NSCachedURLResponse *)connection:(NSURLConnection *)connection
                 willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
    NSCachedURLResponse *newCachedResponse = cachedResponse;
 
    if ([[[[cachedResponse response] URL] scheme] isEqual:@"https"]) {
        newCachedResponse = nil;
    } else {
        NSDictionary *newUserInfo;
        newUserInfo = [NSDictionary dictionaryWithObject:[NSCalendarDate date]
                                                 forKey:@"Cached Date"];
        newCachedResponse = [[[NSCachedURLResponse alloc]
                                initWithResponse:[cachedResponse response]
                                    data:[cachedResponse data]
                                    userInfo:newUserInfo
                                    storagePolicy:[cachedResponse storagePolicy]]
                            autorelease];
    }
    return newCachedResponse;
}

Estimating Upload Progress

You can estimate the progress of an HTTP POST upload with the connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite: delegate method. Note that this is not an exact measurement of upload progress, because the connection may fail or the connection may encounter an authentication challenge.

Downloading Data Synchronously

NSURLConnection provides support for downloading the contents of an NSURLRequest in a synchronous manner using the class method sendSynchronousRequest:returningResponse:error:. Using this method is not recommended, because it has severe limitations:

  • The client application blocks until the data has been completely received, an error is encountered, or the request times out.

  • Minimal support is provided for requests that require authentication.

  • There is no means of modifying the default behavior of response caching or accepting server redirects.

If the download succeeds, the contents of the request are returned as an NSData object and an NSURLResponse for the request is returned by reference. If NSURLConnection is unable to download the URL, the method returns nil and any available NSError instance by reference in the appropriate parameter.

If the request requires authentication in order to make the connection, valid credentials must already be available in the NSURLCredentialStorage, or must be provided as part of the requested URL. If the credentials are not available or fail to authenticate, the URL loading system responds by sending the NSURLProtocol subclass handling the connection a continueWithoutCredentialForAuthenticationChallenge: message.

When a synchronous connection attempt encounters a server redirect, the redirect is always honored. Likewise the response data is stored in the cache according to the default support provided by the protocol implementation.


 

【上篇】
【下篇】

抱歉!评论已关闭.