iOS development GET, POST request method: Nsurlsession

Source: Internet
Author: User

Nsurlsession, and Nsurlconnection are tied, and can support background related network operation of the new features; unlike Nsurlconnection, Nsurlsession replaced Nsurlconnection with Nsurlsession, Nsurlsessionconfiguration,nsurlsessiontask.

Nsurlsession generally have two operations: first, create a task from an instance of Nsurlsession, and second, execute a task;

and Nsurlsessiontask, or task, can be regarded as a so-called task.

Nsurlsessiontask is an abstract subclass that has three specific subclasses that can be used directly: Nsurlsessiondatatask,nsurlsessionuploadtask and Nsurlsessiondownloadtask. These three classes apply three basic network tasks: Get data, upload files, download files. Data-related nsurlsessiondatatask are also capable of uploading and downloading tasks, so they are often used.

———— Example ———— –

First, Get method

123456789101112131415 // 1.创建一个网络路径NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://172.16.2.254/php/phonelogin?yourname=%@&yourpas=%@&btn=login",yourname,yourpass]];// 2.创建一个网络请求NSURLRequest *request =[NSURLRequest requestWithURL:url];// 3.获得会话对象NSURLSession *session = [NSURLSession sharedSession];// 4.根据会话对象,创建一个Task任务:NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {        NSLog(@"从服务器获取到数据");         /*           对从服务器获取到的数据data进行相应的处理:         */NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];    }];    // 5.最后一步,执行任务(resume也是继续执行):    [sessionDataTask resume];

Second, POST method

12345678910111213141516171819 // 1.创建一个网络路径NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://172.16.2.254/php/phonelogin"]];// 2.创建一个网络请求,分别设置请求方法、请求参数NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];request.HTTPMethod = @"POST";NSString *args = [NSString stringWithFormat:@"yourname=%@&yourpass=%@&btn=login",yourname,yourpass];request.HTTPBody = [args dataUsingEncoding:NSUTF8StringEncoding];// 3.获得会话对象NSURLSession *session = [NSURLSession sharedSession];// 4.根据会话对象,创建一个Task任务NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {NSLog(@"从服务器获取到数据");/*对从服务器获取到的数据data进行相应的处理.*/NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];}];//5.最后一步,执行任务,(resume也是继续执行)。[sessionDataTask resume];

Three, nsurlsessiondatadelegate agent method

From the previous two methods, we can see that compared to Nsurlconnection,nsurlsession provides the block way to handle the return data of the simple way, but if the project needs to be in the network request data process, to do further processing, You need to invoke the proxy method for nsurlsession.

In general, the proxy method needs to be set first, but by looking at the Nsurlsessiondatadelegate document, we can see that the Proxy property delegate is read-only.

1 @property (nullable, readonly, retain) id  delegate;

So what do we need to set up proxy objects? Below we demonstrate the use of proxy methods through code:

First, add the agent protocol at the beginning of the file.

123 #import@interface ViewController : UIViewController   //遵循代理协议@end

The Main method is written as follows:

123456789 // 1.delegateQueue参数表示协议方法将会在(NSOperationQueue)队列里面执行。(session的delegate属性是只读的,所以使用如下方法设置代理。)NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]delegate:selfdelegateQueue:[[NSOperationQueue alloc] init]];// 2.创建任务(因为要使用代理方法,就不需要block方式的初始化了)NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://172.16.2.254/php/phonelogin?yourname=%@&yourpass=%@&btn=login",yourname,yourpass]];NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:url]];// 3.执行任务[task resume];

About agent Behavior:

123456789101112131415161718192021 #pragma mark -- NSURLSessionDataDelegate// 1.接收到服务器的响应- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {//【注意:此处需要允许处理服务器的响应,才会继续加载服务器的数据。 若在接收响应时需要对返回的参数进行处理(如获取响应头信息等),那么这些处理应该放在这个允许操作的前面。】completionHandler(NSURLSessionResponseAllow);}// 2.接收到服务器的数据(此方法在接收数据过程会多次调用)- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {    // 处理每次接收的数据,例如每次拼接到自己创建的数据receiveData    [self.receiveData appendData:data];}// 3.3.任务完成时调用(如果成功,error == nil)- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {    if(error == nil){        /*          请求完成,成功或者失败的处理        */    }    else{        NSLog(@"请求失败:%@",error);    }}

Iv. Nsurlsessiondownloadtask

1.NSURLSessionDownloadTask: File Download task

1234567891011121314151617 // 1.创建网路路径NSURL *url = [NSURL URLWithString:@"http://172.16.2.254/php/phonelogin/image.png"] ;// 2.获取会话NSURLSession *session = [NSURLSession sharedSession];// 3.根据会话,创建任务NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {        /*         a.location是沙盒中tmp文件夹下的一个临时url,文件下载后会存到这个位置,由于tmp中的文件随时可能被删除,所以我们需要自己需要把下载的文件移动到其他地方:pathUrl.         b.response.suggestedFilename是从相应中取出文件在服务器上存储路径的最后部分,例如根据本路径为,最后部分应该为:“image.png”         */     NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];        NSURL *pathUrl = [NSURL fileURLWithPath:path];        // 剪切文件        [[NSFileManager defaultManager] moveItemAtURL:location toURL:pathUrl error:nil];    }];// 4.启动任务[task resume];

2.NSURLSessionDownloadDelegate Proxy Method:

Add Protocol First

123 #import@interface ViewController : UIViewController   //遵循代理协议@end

The proxy method is as follows:

123456789101112131415161718192021222324 // 1.每次写入调用(会调用多次)- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {    // 可在这里通过已写入的长度和总长度算出下载进度    CGFloat progress = 1.0 * totalBytesWritten / totalBytesExpectedToWrite; NSLog(@"%f",progress);}// 2.下载完成时调用- (void)URLSession:(NSURLSession *)session      downloadTask:(NSURLSessionDownloadTask *)downloadTaskdidFinishDownloadingToURL:(NSURL *)location {    //  这里的location也是一个临时路径,需要自己移动到需要的路径(caches下面)    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];    [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:nil];}// 3.请求成功/失败(如果成功,error为nil)- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {    if(error == nil){        /*         请求完成,成功或者失败的处理         */    }    else{        NSLog(@"请求失败:%@",error);    }}

Wu, Nsurlsessionuploadtask

1. There are 2 ways to upload files Nsurlsessionuploadtask:

    • Get method:

12 NSURLSessionUploadTask *task =[[NSURLSession sharedSession] uploadTaskWithRequest:request fromFile:fileNamecompletionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {}];

Post method:

1234 [[NSURLSession sharedSession] uploadTaskWithRequest:request fromData:bodycompletionHandler:^(NSData data, NSURLResponse response, NSError *error) {  NSLog(@"-------%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);}];

Different points, is that the Post method needs to add the network path request body body, and in the actual development, upload files generally use post method, more secure and reliable.

Other:

Of course, there are more ways to execute projects that are developed using nsurlsession, and we need to find out more about the daily development process to better use this newer network interface. For example, after the AFNetWorking2.0 version, there is the use of nsurlsession-based packaging, specific interested children's shoes can go to GitHub to understand.

iOS Development GET, POST request method: Nsurlsession article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.