`
jsntghf
  • 浏览: 2477621 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

NSURLConnection的用法

    博客分类:
  • iOS
阅读更多

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:TOP_APPS_URL]];
NSURLConnection *topAppsConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
if (topAppsConnection)
    self.topAppsData = [NSMutableData data];
 

下面是NSURLConnection的几个代理方法:

 

#pragma mark NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSInteger status = [(NSHTTPURLResponse *)response statusCode];
    
    if (status != 200)
        [self cancel:connection];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [topAppsData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [self cancel:connection];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *topAppsString = [[[NSString alloc] initWithData:topAppsData encoding:NSUTF8StringEncoding] autorelease];
    self.topAppsData = nil;
    
    @try {
        RootViewController *rootViewController = (RootViewController *)[navigationController.viewControllers objectAtIndex:0];
        rootViewController.topApps = [[[topAppsString JSONValue] objectForKey:@"feed"]objectForKey:@"entry"];
        [self.window addSubview:navigationController.view];
    }
    @catch (NSException *e) {
        
    }
}

 

接下来,就是这几个代理方法中用到的cancel:函数的实现:

 

- (void)cancel:(NSURLConnection *)connection {
    [connection cancel];
    self.topAppsData = nil;
}

 

具体的例子可以到自定义UIScrollView进行下载。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics