NSURLConnection异步请求

来源:互联网 发布:b*算法Java 编辑:程序博客网 时间:2024/04/28 09:58

NSURLConnection异步请求

对于NSURLConnection在5.0后有两种方法实现异步请求,一种是5.0以后引入的+sendAsynchronousRequest:queue:completionHandler:,还有就是2.0就存在的+connectionWithRequest: delegate:。前一种方法当然是最方便的,而且文档全。但是考虑到兼容的问题,往往还是会采用后者,但是问题在于文档的不全,会让人引起混乱,尽管有一个例子SimpleURLConnection的例子。

+sendAsynchronousRequest:queue:completionHandler:

- (void)loadDataSource {    NSString *URLPath = [NSString stringWithFormat:@"http://imgur.com/gallery.json"];    NSURL *URL = [NSURL URLWithString:URLPath];    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {       NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];       if (!error && responseCode == 200) {          id res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];          if (res && [res isKindOfClass:[NSDictionary class]]) {             self.items = [res objectForKey:@"gallery"];             [self dataSourceDidLoad];          } else {             [self dataSourceDidError];          }       } else {          [self dataSourceDidError];       }    }];}

+connectionWithRequest: delegate:

- (void)loadDataSource {    NSString *URLPath = [NSString stringWithFormat:@"http://imgur.com/gallery.json"];    NSURL *URL = [NSURL URLWithString:URLPath];    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];       [NSURLConnection connectionWithRequest:request delegate:self];}//---------------------------------------// You have to implement below four methods//---------------------------------------- (void)connection:(NSURLConnection *)theConnection didReceiveResponse:(NSURLResponse *)response{    NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];    _connectedSuccess = responseCode == 200;    NSLog(@"response length=%lld", [response expectedContentLength]);}- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data// A delegate method called by the NSURLConnection as data arrives.  The // response data for a POST is only for useful for debugging purposes, // so we just drop it on the floor.{    if (_galleryData == nil) {        _galleryData = [[NSMutableData alloc] initWithData:data];    } else {        [_galleryData appendData:data];    }}- (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error// A delegate method called by the NSURLConnection if the connection fails. // We shut down the connection and display the failure.  Production quality code // would either display or log the actual error.{}- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection// A delegate method called by the NSURLConnection when the connection has been // done successfully.  We shut down the connection with a nil status, which // causes the image to be displayed.{    if (_connectedSuccess) {        id res = [NSJSONSerialization JSONObjectWithData:_galleryData options:NSJSONReadingMutableContainers error:nil];        if (res && [res isKindOfClass:[NSDictionary class]]) {            self.items = [res objectForKey:@"gallery"];            [self dataSourceDidLoad];        } else {            [self dataSourceDidError];        }        [_galleryData release];        _galleryData = nil;    } else {        [self dataSourceDidError];    }}

实际上必须要实现NSURLConnectionDataDelegate,而这个Protocol的声明在文档中是不容易找到的,只有在这里提到了一下,在SimpleURLConnection中则没有说清楚。不过估计在5.0以前应该是没有这个Protocol的,所以在实现的过程中只要增加这四个方法就可以了,也可以有选择性地增加你想要地因为都是可选地方法。注意在这个代码里面用到了NSJSONSerialization,这个也是5.0引入的,所以要想用JSON Parser可以考虑JSONKit。

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 1岁半高烧39度怎么办 反复发烧39度多怎么办 孩子不爱喝水怎么办%3f 8岁儿童不爱喝水怎么办 儿子14岁了不爱说话怎么办 我孩子长得老慢怎么办 老公嫌你烦了怎么办 2岁宝宝吃饭不嚼怎么办 2岁宝宝挑食厌食怎么办 孩子不爱和家长交流怎么办 孩子发烧在医院查不出病因怎么办 宝宝乳牙长歪了怎么办 两岁宝宝不爱吃水果怎么办 两岁宝宝不吃水果怎么办 一岁的宝宝上火了怎么办 吃水果嘴唇肿了怎么办 二岁宝宝不爱吃饭怎么办 小婴儿便秘但不爱喝水怎么办 宝宝只吃水果不吃饭怎么办 一岁宝宝不喜欢吃水果怎么办 1岁宝宝不吃水果怎么办 一岁半宝宝吃水果拉肚子怎么办 大人发烧了怎么办如何退烧 怀孕后不爱吃水果怎么办 不敢吃水果了怕虫怎么办 宝宝发烧38度不出汗怎么办 1岁宝宝喜欢含饭怎么办 3岁宝宝喜欢含饭怎么办 孩子咳嗽发烧怎么办最有效 孩子咳嗽打哈切流鼻涕发烧怎么办 孩子香蕉吃多了怎么办 80多岁老人发烧怎么办 小孩香蕉吃多了怎么办 7个月宝宝缺钙怎么办 宝宝脖子被汗淹到红了脱皮怎么办? 小儿出汗多咳嗽怎么办吃什么 牛高烧不退怎么办最好 猪体温低不吃食怎么办 小孩发烧咳嗽怎么办吃什么药 大晚上发烧39度怎么办 胃受凉了老打嗝怎么办