NSURLConnection的用法

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进行下载。

你可能感兴趣的:(ios,iPhone,NSURLConnection)