if (connection) {
_datas = [NSMutableData new];
}
}
#pragma mark- NSURLConnection 回调方法
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
①
[_datas appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError: (NSError *)error {
NSLog(@”%@”,[error localizedDescription]);
}
- (void) connectionDidFinishLoading: (NSURLConnection*) connection {
②
NSLog(@”请求完成…”);
NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:_datas
options:NSJSONReadingAllowFragments error:nil];
[self reloadView:dict];
}
在第①行的 connection:didReceiveData:方法中,通过[_datas appendData:data]语句不断地
接收服务器端返回的数据,理解这一点是非常重要的。如果加载成功就回调第 ②行的
connectionDidFinishLoading: 方法,这个方法被回调也意味着这次请求的结束,这时候
_datas 中的数据是完整的,在这里把数据发送回表示层的视图控制器。