码迷,mamicode.com
首页 > 其他好文 > 详细

QF——网络之网络请求

时间:2015-03-31 12:13:12      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

NSURLConnection:

  这是自带的网络请求类。它的思路是建立连接的同时设置自己为自己的代理,然后就实现协议的几个方法(didReceiveResponse,didReceiveData,connectionDidFinishLoading,didFailWithError)。其中didReceiveData可能会被调用多次,因为当服务器传过来的数据很大时,它会分段传,每次传一点。所以我们得用可变NSMutableData来存储接收的数据。当所有数据接收完成后,connectionDidFinishLoading方法会被自动调用,在该方法里我们可以完成解析json数据的动作(服务器传过来的数据是json格式的)。

同步请求和异步请求:

  同步请求会阻塞主线程;

  异步请求不会阻塞主线程。

 

//
//  ViewController.m
//  JSONTest
//
//  Created by mac on 15-3-30.
//  Copyright (c) 2015年 ___FULLUSERNAME___. All rights reserved.
//

#import "ViewController.h"
#import "App.h"
#import "UIImageView+WebCache.h"
#define kSearchUrl @"https://api.douban.com/v2/book/search?q=s"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,NSURLConnectionDataDelegate,NSURLConnectionDelegate>
{
    NSMutableArray * appArr;
    NSMutableData * downloadData;
    
    UITableView * tabView;
}

@end

@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    downloadData = [NSMutableData data];
    appArr = [NSMutableArray array];
    
    //新建tableView
    [self createTableView];
    
    //建立异步请求
    [self makeConnection];
    
    
    
}

- (void)createTableView
{
    tabView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 480) style:UITableViewStyleGrouped];
    tabView.delegate = self;
    tabView.dataSource = self;
    tabView.rowHeight = 80;
    [self.view addSubview:tabView];
    
//    [tabView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
}

- (void)makeConnection
{
    [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:kSearchUrl]] delegate:self];
    
}

- (void)decodeJson:(NSMutableData *)data
{
    NSError * error;
    NSDictionary * jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    NSArray * jsonArr = jsonDict[@"books"];
    for(NSDictionary * dict1 in jsonArr)
    {
        NSString * large = dict1[@"images"][@"large"];
        NSString * title = dict1[@"title"];
        NSString * author = dict1[@"author"][0];
        
        App * app = [[App alloc]init];
        app.large = large;
        app.title = title;
        app.author = author;
        
        [appArr addObject:app];
    }
    
    NSLog(@"%d",appArr.count);
   
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return appArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(cell==nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        
        if(appArr.count>0)
        {
            App * app = appArr[indexPath.row];
            cell.textLabel.text = app.title;
            cell.detailTextLabel.text = app.author;
            [cell.imageView sd_setImageWithURL:[NSURL URLWithString:app.large] placeholderImage:[UIImage imageNamed:@"photo"]];
        }
    }
    
    return cell;
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    downloadData.length = 0;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [downloadData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //解析json数据
    [self decodeJson:downloadData];
    [tabView reloadData];
    
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%@",error);
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end

 

第三方网络请求框架AFHTTPRequestOperationManager:

  先一个请求管理类,然后调用下面一个方法就行了,它里面只需要两个参数url和param,然后有两个请求成功和失败的回调方法(block)。success的block返回值responseObject就是服务器传过来的完整数据。

  可以在success的block里完成数据解析。

    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    [manager GET:kSearchUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"请求成功");
        //responseObject就是传过来的数据,而且是一次性完整的数据。可以在这里完成数据解析工作
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"请求失败");
    }];

 

QF——网络之网络请求

标签:

原文地址:http://www.cnblogs.com/wangerxiansheng/p/4380242.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!