网络请求(17-08-16)

2017-08-16  本文已影响0人  Hilarylii
//
//  ViewController.m
//  UI10_Network
//
//  Created by lanou3g on 17/8/16.
//  Copyright © 2017年 lanou3g. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, retain) UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 100, 100);
    button.backgroundColor = [UIColor greenColor];
    [button setTitle:@"hahaha" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonAction1:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 300, 100, 100)];
    imageView.backgroundColor = [UIColor redColor];
    [self.view addSubview:imageView];
    self.imageView = imageView;
    
    
}

- (void)buttonAction:(UIButton *)button {
    NSLog(@"button action");
    
    NSURL *url = [NSURL URLWithString:@"http://img5.duitang.com/uploads/item/201410/02/20141002122659_dZcJH.jpeg"];
    NSData *data = [[NSData alloc] initWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];
    self.imageView.image = image;
}
//异步请求
- (void)buttonAction1:(UIButton *)button {
    //会话  根据URL字符串生成URL对象
    NSURL *url = [NSURL URLWithString:@"http://img5.duitang.com/uploads/item/201410/02/20141002122659_dZcJH.jpeg"];
    
    //根据URL对象生成对应的Request请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方法(GET,POST),默认数GET
    request.HTTPMethod = @"GET";
    //请求的超时时间
    request.timeoutInterval = 60.f;
    //请求主体
    request.HTTPBody = [@"主题内容" dataUsingEncoding:NSUTF8StringEncoding];
    
    //获取系统的URL会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    //会话对象(session)根据一个具体的请求(request)生成一个任务(task)
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //将操作在主线程中执行(PS:所有的UI刷新操作要求开发者必须在主线程中执行)
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"返回结果");
            if (!error) {
                
                //如果请求回的数据是Json,做json解析
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                
                //如果错误对象为空(表示请求成功),做对应的数据处理操作
                UIImage *image = [UIImage imageWithData:data];
                self.imageView.image = image;
            } else {
                //错误对象(error)不为空(表示请求错误),查看错误信息
                NSLog(@"error:%@",error);
            }
        });
        //拓展:
        //延时线程
        //参数1:延时秒数
        //参数2:要延时的操作
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            NSLog(@"");
//        });
    }];
    //启动任务:去做网络请求
    [dataTask resume];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

上一篇下一篇

猜你喜欢

热点阅读