2011年3月26日 星期六

Download File Asynchronously

利用NSURLConnection的initWithRequest:delegate:startImmediately: method建立connection,
於startImmediately傳入yes表示馬上開始download
NSURL *url = [NSURL URLWithString:urlStr];
self.downloadData = [[NSMutableData alloc] init];
[self.downloadData release];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
self.downloadConnection = [[NSURLConnection alloc
                                   initWithRequest:req  
                                   delegate:self
                                   startImmediately:YES];
[self.downloadConnection release];


常用的NSURLConnectionDelegate method


開始download後,首先被呼叫的method
由於一個request可能收到多個response,
所以將data的長度設為0,
清除之前收到的data


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"didReceiveResponse");
    [self.downloadData setLength:0];
}

將收到的data累加進downloadData
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"data %d", [data length]);
    [self.downloadData appendData:data];

}

成功完成下載時被呼叫
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Successfully connectionDidFinishLoading");

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"error %@", error);
}


測試輸出:

2011-03-26 17:50:00.690 DownloadAsync[13125:207] didReceiveResponse
2011-03-26 17:50:00.692 DownloadAsync[13125:207] data 3310
2011-03-26 17:50:00.693 DownloadAsync[13125:207] data 13258
2011-03-26 17:50:00.694 DownloadAsync[13125:207] Successfully connectionDidFinishLoading



沒有留言:

張貼留言