iOS用原生NSURLSession进行网络请求

2018-09-20  本文已影响9人  lllaa

1.概况



2.使用步骤

1.创建会话NSURLSession(三种方式)

2.创建task(可创建三种类型的task)

3.开始任务

具体的步骤如下

2.1.创建NSURLSession ()

三种创建方式:

1)直接创建

NSURLSession *session=[NSURLSession sharedSession];

(2)配置后创建

[NSURLSession  sessionWithConfiguration:defaultSessionConfiguration];

(3)设置加代理获得

//使用代理方法需要设置代理,但是session的delegate属性是只读的,要想设置代理只能通过这种方式创建session

NSURLSession *session=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]

delegate:self

delegateQueue:[[NSOperationQueuealloc]init]];

2.2创建Task

NSURLSessionDataTask 普通任务

NSURLSessionDownloadTask 下载任务

NSURLSessionUploadTask上传任务

1.get请求 

创建方式主要有两种

GET1 : 使用request创建task

- (void)jsonTest {

    NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];

    NSString * url = [NSString stringWithFormat:@"http://api.androidhive.info/volley/person_object.json"];

    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];

    NSURLSessionDataTask * task = [session dataTaskWithRequest:request];

    self.task = task;

}

GET2: 使用URL创建Task

//图片请求 get

- (void)imgTest {

    NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];

    //这是个gif图、懒得弄了。方便暂停用的

    NSString * url = [NSString stringWithFormat:@"https://upfile.asqql.com/2009pasdfasdfic2009s305985-ts/2018-4/2018423202071807.gif"];

    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];

    NSURLSessionDataTask * task = [session dataTaskWithRequest:request];

    self.task = task;

}

2.post请求

在上传任务里

//图片上传 post

- (void)upDataTest {

    NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];

    //这是个gif图、懒得弄了。方便暂停用的

    NSString * url = [NSString stringWithFormat:@"http://www.chuantu.biz/upload.php"];

    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];

    request.HTTPMethod = @"POST";

    NSString *path = [[NSBundle mainBundle]pathForResource:@"tu" ofType:@"gif"];

    NSURLSessionUploadTask * task = [session uploadTaskWithRequest:request fromFile:[NSURL URLWithString:path]];

    self.task = task;

}

下载任务创建task

//下载任务

- (void)downLoadTest {

    NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];

    //这是个gif图、懒得弄了。方便暂停用的

    NSString * url = [NSString stringWithFormat:@"https://upfile.asqql.com/2009pasdfasdfic2009s305985-ts/2018-4/2018423202071807.gif"];

    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];

    NSURLSessionDownloadTask * task;

    if (self.resumeData) {

        //需要服务器支持断点续传

        task = [session downloadTaskWithResumeData:self.resumeData];

    }else {

        task = [session downloadTaskWithRequest:request];

    }

    self.task = task;

}

2.3开始任务

[self.task resume];开始

[self.task cancel];取消

[self.task suspend];暂停

用原生的网络封装一个get post请求

get请求

+ (void)getWithUrlString:(NSString *)url parameters:(id)parameters success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock

{

    NSMutableString *mutableUrl = [[NSMutableString alloc] initWithString:url];

    if ([parameters allKeys]) {

        [mutableUrl appendString:@"?"];

        for (id key in parameters) {

            NSString *value = [[parameters objectForKey:key] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

            [mutableUrl appendString:[NSString stringWithFormat:@"%@=%@&", key, value]];

        }

    }

    NSString *urlEnCode = [[mutableUrl substringToIndex:mutableUrl.length - 1] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlEnCode]];

    NSURLSession *urlSession = [NSURLSession sharedSession];

    NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:urlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        if (error) {

            failureBlock(error);

        } else {

            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

            successBlock(dic);

        }

    }];

    [dataTask resume];

}

post请求

+ (void)postWithUrlString:(NSString *)url parameters:(id)parameters success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock

{

    NSURL *nsurl = [NSURL URLWithString:url];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:nsurl];

    //如果想要设置网络超时的时间的话,可以使用下面的方法:

    //NSMutableURLRequest *mutableRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    //设置请求类型

    request.HTTPMethod = @"POST";

    NSString *postStr = [NetworkManager parseParams:parameters];

    //把参数放到请求体内

    request.HTTPBody = [postStr dataUsingEncoding:NSUTF8StringEncoding];

    NSURLSession *session = [NSURLSession sharedSession];

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

        if (error) { //请求失败

            failureBlock(error);

        } else {  //请求成功

            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

            successBlock(dic);

        }

    }];

    [dataTask resume];  //开始请求

}

//把NSDictionary解析成post格式的NSString字符串

+ (NSString *)parseParams:(NSDictionary *)params

{

    NSString *keyValueFormat;

    NSMutableString *result = [NSMutableString new];

    NSMutableArray *array = [NSMutableArray new];

    //实例化一个key枚举器用来存放dictionary的key

    NSEnumerator *keyEnum = [params keyEnumerator];

    id key;

    while (key = [keyEnum nextObject]) {

        keyValueFormat = [NSString stringWithFormat:@"%@=%@&", key, [params valueForKey:key]];

        [result appendString:keyValueFormat];

        [array addObject:keyValueFormat];

    }

    return result;

}

参考:

NSURLSession &AFN &网络监测

NSUrlSession专题

文件上传和断点离线下载

上一篇 下一篇

猜你喜欢

热点阅读