iOS_网络请求_代理方式

#pragma mark - 网络请求代理方式(异步)
- (IBAction)DelegateButtonDidClicked:(UIButton *)sender {

    // 1、拼接 urlString,网址里面必须写 http://
    NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";

    // 2、根据字符串创建 URL(统一资源定位符)
    NSURL *url = [NSURL URLWithString:urlString];

    // 3、根据 url 创建 request 请求类的对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    // 4、请求数据(代理回调方式)遵守代理 <NSURLConnectionDataDelegate>
    [NSURLConnection connectionWithRequest:request delegate:self];
}

代理方法
客户端收到服务器的响应

#pragma mark | 客户端收到服务器的响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // 只执行一次
    // 初始化 receiveData 对象
    self.receiveData = [NSMutableData data];
}

客户端收数据(并非一次性全部拿到)

#pragma mark | 客户端收数据(并非一次性全部拿到)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // 每次返回的都是新数据
    // 拼接数据(请求一点 拼接一点)
    [self.receiveData appendData:data]; }

客户端接收数据完毕

#pragma mark | 客户端接收数据完毕
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // 解析数据
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.receiveData options:(NSJSONReadingMutableContainers) error:nil];


    NSArray *array = dict[@"news"];

    self.newsArray = [NSMutableArray array];

    for (NSDictionary *smallDict in array) {
        NewsModal *modal = [[NewsModal alloc] init];
        [modal setValuesForKeysWithDictionary:smallDict];
        [self.newsArray addObject:modal];
    }

    for (NewsModal *modal in self.newsArray) {
        NSLog(@"%@", modal.title);
    }
}

网络请求失败

#pragma mark | 网络请求失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%@", error);
}

你可能感兴趣的:(ios,网络请求,代理)