2013年10月29日 星期二

HttpRequest : get資料

-(void)asyncDownloadInfoForBookAtURL:(NSURL *)url
{
    // Download the info for this book
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease];
    [request setHTTPMethod:@"GET"];
   
    // Do not start the network operation immediately
    NSURLConnection *aConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
   
    // Use the run loop associated with the main thread
    [aConnection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
   
    // Start the network operation
    [aConnection start];
}

delegate (委派)有四個

// 開始接收資料,會呼叫此方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
當系統開始要接收資料的時候這個方法會被呼叫到
要把這 responseData 給清空,如果UI上有ProgressBar的話要將之歸零

// 接收新的資料時,會呼叫此方法
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
每次資料在下載的時候,會不停的呼叫這個方法
可以看到這個data傳入的參數,就是每一小塊一小塊的資料
我們只要把它累加起來即可,如果UI上有ProgressBar的話就可以慢慢累加1

// 下載完畢時,會呼叫此方法
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
最後跑完會呼叫這個方法,就是你需要做處理的部分
例如顯示到畫面上,存入SQLite....等等


// 連線錯誤時,會呼叫此方法
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
最後就是這個,中間若有網路錯誤等因素就會呼叫這個方法
你可以跳一個提示框或是印Log

沒有留言:

張貼留言