網(wǎng)絡(luò)請(qǐng)求(17-08-16)

//
//  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;
}
//異步請(qǐng)求
- (void)buttonAction1:(UIButton *)button {
    //會(huì)話  根據(jù)URL字符串生成URL對(duì)象
    NSURL *url = [NSURL URLWithString:@"http://img5.duitang.com/uploads/item/201410/02/20141002122659_dZcJH.jpeg"];
    
    //根據(jù)URL對(duì)象生成對(duì)應(yīng)的Request請(qǐng)求對(duì)象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //設(shè)置請(qǐng)求方法(GET,POST),默認(rèn)數(shù)GET
    request.HTTPMethod = @"GET";
    //請(qǐng)求的超時(shí)時(shí)間
    request.timeoutInterval = 60.f;
    //請(qǐng)求主體
    request.HTTPBody = [@"主題內(nèi)容" dataUsingEncoding:NSUTF8StringEncoding];
    
    //獲取系統(tǒng)的URL會(huì)話對(duì)象
    NSURLSession *session = [NSURLSession sharedSession];
    //會(huì)話對(duì)象(session)根據(jù)一個(gè)具體的請(qǐng)求(request)生成一個(gè)任務(wù)(task)
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //將操作在主線程中執(zhí)行(PS:所有的UI刷新操作要求開發(fā)者必須在主線程中執(zhí)行)
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"返回結(jié)果");
            if (!error) {
                
                //如果請(qǐng)求回的數(shù)據(jù)是Json,做json解析
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                
                //如果錯(cuò)誤對(duì)象為空(表示請(qǐng)求成功),做對(duì)應(yīng)的數(shù)據(jù)處理操作
                UIImage *image = [UIImage imageWithData:data];
                self.imageView.image = image;
            } else {
                //錯(cuò)誤對(duì)象(error)不為空(表示請(qǐng)求錯(cuò)誤),查看錯(cuò)誤信息
                NSLog(@"error:%@",error);
            }
        });
        //拓展:
        //延時(shí)線程
        //參數(shù)1:延時(shí)秒數(shù)
        //參數(shù)2:要延時(shí)的操作
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            NSLog(@"");
//        });
    }];
    //啟動(dòng)任務(wù):去做網(wǎng)絡(luò)請(qǐng)求
    [dataTask resume];
}

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


@end

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容