美文网首页网络详解
NSURLSession发送GET-POST-DOWNLOAD请

NSURLSession发送GET-POST-DOWNLOAD请

作者: solozyx | 来源:发表于2016-08-07 20:01 被阅读98次

    block方式处理返回结果:

    - (void)get{
        // 获得NSURLSession对象
        NSURLSession *session = [NSURLSession sharedSession];
        // 创建任务
        NSString *urlString = @"http://www.example.com:8080/login?username=solozyx&pwd=solozyx";
        NSURL *url = [NSURL URLWithString:urlString];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                    if (error == nil) {
                                                        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
                                                                                                             options:NSJSONReadingMutableContainers
                                                                                                               error:nil];
                                                        NSLog(@"%@", dict); // {"success":"登录成功"}
                                                    }
                                                }];
        // 启动任务
        [task resume];
    }
    
    - (void)get2{
        NSURLSession *session = [NSURLSession sharedSession];
        NSString *urlString = @"http://www.example.com:8080/login?username=solozyx&pwd=solozyx";
        NSURL *url = [NSURL URLWithString:urlString];
        NSURLSessionDataTask *task = [session dataTaskWithURL:url
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
                                                // {"success":"登录成功"}
                                            }];
        [task resume];
    }
    
    - (void)post{
        NSURLSession *session = [NSURLSession sharedSession];
    
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com:8080/login"]];
        request.HTTPMethod = @"POST";
        request.HTTPBody = [@"username=solozyx&pwd=solozyx" dataUsingEncoding:NSUTF8StringEncoding];
        
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                    NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
                                                    // {"success":"登录成功"}
                                                }];
        [task resume];
    }
    
    
    - (void)download{
        NSURLSession *session = [NSURLSession sharedSession];
        NSString *urlString = @"http://www.example.com:8080/resources/videos/minion_01.mp4";
        NSURL *url = [NSURL URLWithString:urlString];
        NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url
                                                    completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
                                                        if (error == nil) {
                                                            // 文件将来存放的真实路径
                                                            NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
                                                            // 剪切location的临时文件到真实路径
                                                            NSFileManager *mgr = [NSFileManager defaultManager];
                                                            [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
                                                            NSLog(@"%@",file);
                                                        }
                                                    }];
        [task resume];
    }
    

    delegate方式处理返回结果:
    <NSURLSessionDataDelegate>

    #import "ViewController.h"
    
    @interface ViewController () <NSURLSessionDataDelegate>
    
    @end
    
    
    @implementation ViewController
    
    - (void)startDataDask {
        // 获得NSURLSession对象
        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
                                                              delegate:self
                                                         delegateQueue:[[NSOperationQueue alloc] init]];
        // 创建任务
        NSString *urlString = @"http://www.example.com:8080/login?username=solozyx&pwd=solozyx";
        NSURL *url = [NSURL URLWithString:urlString];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
        // 启动任务
        [task resume];
    }
    
    #pragma mark - <NSURLSessionDataDelegate>
    /**
     * 1.接收到服务器的响应
     */
    - (void)URLSession:(NSURLSession *)session
              dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveResponse:(NSURLResponse *)response
     completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
        NSLog(@"%s", __func__);
        // 允许处理服务器的响应,才会继续接收服务器返回的数据
        completionHandler(NSURLSessionResponseAllow);
    }
    
    /**
     * 2.接收到服务器的数据(可能会被调用多次)
     */
    - (void)URLSession:(NSURLSession *)session
              dataTask:(NSURLSessionDataTask *)dataTask
        didReceiveData:(NSData *)data{
        NSLog(@"%s", __func__);
    }
    
    /**
     * 3.请求成功或者失败(如果失败,error有值)
     */
    - (void)URLSession:(NSURLSession *)session
                  task:(NSURLSessionTask *)task
    didCompleteWithError:(NSError *)error{
        NSLog(@"%s", __func__);
    }
    
    @end
    
    // -[ViewController URLSession:dataTask:didReceiveResponse:completionHandler:]
    // -[ViewController URLSession:dataTask:didReceiveData:]
    // -[ViewController URLSession:task:didCompleteWithError:]
    

    相关文章

      网友评论

        本文标题:NSURLSession发送GET-POST-DOWNLOAD请

        本文链接:https://www.haomeiwen.com/subject/obmlsttx.html