Tableview 数据异步加载

1 LazyTableImages

2 http://nsscreencast.com/episodes/6-afnetworking  

AFNetworking 中的方法:

[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];

3 异步网络请求

- (void)fetchForKeyword:(NSString *)keyword {
    
    // 初始化请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    // 设置URL
    NSString *host = @"http://localhost:3000/";
    NSString *urlstrtemp = [host stringByAppendingString:@"hj_dicts.json?text="];
    NSString *urlstr = [urlstrtemp stringByAppendingString:keyword];
    //注意:URL编码问题
    NSString *sUrl = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)urlstr, nil, nil, kCFStringEncodingUTF8));
    //设置request
    [request setURL:[NSURL URLWithString:sUrl]];
    [request setHTTPMethod:@"GET"];
    //发送异步请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        //出错处理
        NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
        if (!error && responseCode == 200) {
            NSError *e = nil;
            //把JSONData转换为NSArray
            serverData = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &e];
            if(!e){
                [self.tableView reloadData];
            } else {
                //序列化失败
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Serialization failed." message:@"JSON序列化失败" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                    [alert show];
                });
            }
        } else {
            //无法访问网络
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection failed." message:@"无法访问网络" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
            });
        };
    }];
}

猜你喜欢

转载自iandaicsu.iteye.com/blog/1798074