数据的网络请求

来源:互联网 发布:创世数据网站 编辑:程序博客网 时间:2024/06/11 15:28

数据的网络请求有两类: 同步请求和异步请求

又可以归结为三种: 第一种:同步请求, 第二种:异步 Get 协议请求和异步 Get block 请求, 第三种: Post block 请求

     iOS9.0之后,默认是 https 请求, 如果想继续使用 http请求, 需要在info.plist 点右键加一句话

<key>NSAppTransportSecurity</key>

      <dict>

        <key>NSAllowsArbitraryLoads</key>

        <true/>

      </dict>

在进行网络请求操作之前要在工程的 info.plist 文件中粘贴上

1. 同步请求

首先在ViewController中创建UIImageView

#import "ViewController.h"


@interface ViewController ()


- (IBAction)syn:(id)sender;

定义两个属性

@property(nonatomic,retain) UIImageView *imageView;

//用来装每次请求的数据

@property(nonatomic,retain) NSMutableData *data;

@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

//    iOS9.0之后,默认是 https 请求, 如果想继续使用 http请求, 需要在info.plist 点右键加一句话

//    <key>NSAppTransportSecurity</key>

//      <dict>

//        <key>NSAllowsArbitraryLoads</key>

//        <true/>

//      </dict>

    self.imageView = [[UIImageViewalloc] initWithFrame:CGRectMake(140,60, 100, 100)];

    [self.viewaddSubview: self.imageView];

    self.imageView.backgroundColor = [UIColorgrayColor];

    [_imageView release];

}


- (IBAction)syn:(id)sender {

    获取网址的字符串

    NSString *urlStr =@"http://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg";

    //把网址的字符串变成 NSURL

    NSURL *url = [NSURLURLWithString:urlStr];

    // url对应的内容变成 NAData

    NSData *data = [NSDatadataWithContentsOfURL:url];

    self.imageView.image = [UIImageimageWithData:data];

}

2. 异步 Get block 请求

@interfaceViewController ()<NSURLSessionDelegate>


- (IBAction)syn:(id)sender;

- (IBAction)asyProtocolGet:(id)sender;

- (IBAction)asynBlockGet:(id)sender;

- (IBAction)asynBlockPost:(id)sender;

@property(nonatomic,retain) UIImageView *imageView;

//用来装每次请求的数据

@property(nonatomic,retain) NSMutableData *data;



@end


@implementation ViewController


- (void)viewDidLoad

{

    [superviewDidLoad];


}



- (IBAction)asyProtocolGet:(id)sender {

    NSString *strURL =@"http://api.map.baidu.com/place/v2/search?query=银行&region=大连&output=json&ak=6E823f587c95f0148c19993539b99295";

    //一个 url有字母(大小写),数字和特殊符号/,  &,  $,  ?,  =组成, 一般来说没有汉字,所以当请求包里有种有汉字的时候, 需要手动给 url 转码,

    strURL = [strURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSetcharacterSetWithCharactersInString:strURL]];

    NSLog(@"%@", strURL);

    //需要把 strURL转换成 NSURL

    NSURL *url = [NSURLURLWithString:strURL];

    NSData *data = [NSDatadataWithContentsOfURL:url];

    self.imageView.image = [UIImageimageWithData:data];

    //创建一个请求对象

    NSMutableURLRequest *repuest = [NSMutableURLRequestrequestWithURL:url];

    //创建NSURLSecssion对象

    NSURLSession *session = [NSURLSessionsessionWithConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration] delegate:selfdelegateQueue:[NSOperationQueuemainQueue]];

    //创建一个任务对象

    NSURLSessionTask *task = [session dataTaskWithRequest:repuest];

    //执行任务,如果不写, 整个任务不会自动执行

    [task resume];

}


- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask

didReceiveResponse:(NSURLResponse *)response

 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {

    NSLog(@"%@", response);

    //这个方法回吧服务器相应的信息返回给我们,也就是说 response,在这里能查到 http 状态码, status code, 200是请求成功, 404没找到指定页面, 500服务器出问题,所以 response 可以知道请求的相应信息, 便于查找.

    //当服务器相应之后,需要允许服务器相应, 才能继续接受信任方法就是调用第四个参数 block让他完成这个功能

    completionHandler(NSURLSessionResponseAllow);

    //允许完之后,初始化接收数据的容器, data.

    self.data = [NSMutableDatadata];

}


#pragma mark - 这个方法会持续的从服务器接收返回的数据,会被多次调用, 在这个方法里可以用 self.data对数据进行累加, 等到最后一个数据完成之后,就完成了整个请求过程

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask

    didReceiveData:(NSData *)data {

    //累加

    [self.dataappendData:data];

}

#pragma mark - 这个协议方法一般会在完成请求过请求失败的时候出现,区分的话就是参数 error, 如果失败, error 就会有值,反之为空.

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task

didCompleteWithError:(nullable NSError *)error {

    if (error == nil) {

        NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:self.dataoptions:0error:nil];

        NSLog(@"%@", dic);

    } else {

        NSLog(@"请求失败");

    }

}


3. 异步 Get block 请求

#import "ViewController.h"


@interface ViewController ()


- (IBAction)asynBlockGet:(id)sender;


@property(nonatomic,retain) UIImageView *imageView;

//用来装每次请求的数据

@property(nonatomic,retain) NSMutableData *data;


@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    

}


- (IBAction)asynBlockGet:(id)sender {

    NSString *strURL =@"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/activitylist.php";

    NSURL *URL = [NSURLURLWithString:strURL];

    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:URL];

    //创建一个 session对象

    NSURLSession *session = [NSURLSessionsharedSession];

    //创建一个任务对象

    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError * _Nullable error) {

        //json 解析

        NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:dataoptions:0error:nil];

        NSLog(@"%@", dic);

        NSLog(@"%@", response);

    }];

    //执行一下任务

    [task resume];

}


4.异步 Post block 请求

#import "ViewController.h"


@interface ViewController ()


- (IBAction)asynBlockGet:(id)sender;


@property(nonatomicretainUIImageView *imageView;

//用来装每次请求的数据

@property(nonatomicretainNSMutableData *data;


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    

}


- (IBAction)asynBlockPost:(id)sender {

    NSString *str =@"http://api2.pianke.me/pub/today";

    NSURL *url = [NSURLURLWithString:str];

    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url];

    //设置请求方法,默认是 GET

    [request setHTTPMethod:@"POST"];

    

    NSString *bodyStr =@"start=%ld&client=2&limit=10";

    //需要把附件字符转换成 NSData

    NSData *bodyData = [bodyStrdataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPBody:bodyData];

    

    NSURLSession *session = [NSURLSessionsharedSession];

    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError * _Nullable error) {

        NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:dataoptions:0error:nil];

        NSLog(@"%@", dic);

        

    }];

    

    [task resume];

 

}

总结:异步的 Get block 请求用的比较多, 代码数量不多记忆也方便, 但是使用时要注意数据的刷新



0 0
原创粉丝点击