iOS-get异步网络请求-网络数据请求

iOS-get异步网络请求-网络数据请求

iOS-get异步网络请求-网络数据请求
iOS-get异步网络请求-网络数据请求
//
// ViewController.m
// get异步网络请求
//
// Created by YIem on 16/3/1.
// Copyright © 2016年 YIem. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor cyanColor];
    UIButton *getButton = [UIButton buttonWithType:UIButtonTypeSystem];
    getButton.frame = CGRectMake(100, 100, 100, 100);
    [getButton setTitle:@"get网络请求" forState:UIControlStateNormal];
    [getButton addTarget:self action:@selector(getAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:getButton];

}

  • (void)getAction
    {
    // 网络链接
    NSString *urlStr = @"http://api.map.baidu.com/place/v2/search?query=银行&region=大连&output=json&ak=6E823f587c95f0148c19993539b99295";
    // 当网址中有未明字符(如中文)时进行转码
    NSString *urlEncode = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    NSURL *url = [NSURL URLWithString:urlEncode];
    // 请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 配置(默认配置)
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    // 创建请求任务, 当异步请求完成时会调用block
    NSURLSessionDataTask *getTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"--%@", dic);

    }];
    // 开始任务
    [getTask resume];
    }

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

@end

标签: none

添加新评论

Title - Artist
0:00