2013年4月26日 星期五

NSURLRequest

資料來源

有兩個重要的Delegate要實作: NSURLConnectionDataDelegate, NSURLConnectionDelegate
一樣只列出我現在用到的, 其它以後有用到學到再補充

// 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.
}
在connectionWithRequest:delegate 後, 下載會立刻開始, 相當於下面這兩個方法
initWithRequest:delegate: 以及
initWithRequest:delegate:startImmediately:startImmediately=YES
差別在於Instance method以及Class Method以及要不要手動release
不過在有ARC的現在看起來都是一樣的

若不要立刻開始下載動作則
initWithRequest:delegate:startImmediately:startImmediately=NO 就好
之後可再用 [theConnection start] 開始下載

而下載是隨時可以使用 [theConnection cancel] 中斷的, 只要下面在這兩個delegate回應前就好
connectionDidFinishLoading:connection;
connection:didFailWithError:error;



#pragma mark - NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Connection failed! Error - %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
這方法名稱就解釋很清楚, 下載連線有問題(比如沒有3G或Wi-Fi, 或是連線遇時)遇到錯誤的處理



#pragma mark - NSURLConnectionDataDelegate
- (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];
    NSLog(@"%lld", [response expectedContentLength]);
}
官方的註解解釋很清楚, 另外這邊可以得知檔案大小

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere.
    [receivedData appendData:data];
}
官方的註解解釋很清楚, 另外這邊由得知的檔案大小來設定下載進度條

- (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]);
}
官方的註解解釋很清楚, 這裡面可以寫些call其它自己定義的method
例如,若receivedData資料為JSON, 就可以去寫個Parse JSON的method, 然後在這裡面去call寫好的method


- (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];
    }

}
這方法在寫這篇文章的時候才知道用途, 實際應用上的話要看做Server那邊的人
這方法只有在response的headers內有"Cache-Control"才會被呼叫
裡面的內容我暫時不知道該怎樣寫, 還在學習中

沒有留言:

張貼留言