iOS-NSURLSession简单使用

废话不多说,直奔主题

NSURLSession GET 使用block 请求

 //请求地址,此处是图片的url,具体使用可以换成对应的url
    NSURL *url=[NSURL URLWithString:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1490091074375&di=03327b9db0e521fd5a60c0a1475b76ae&imgtype=0&src=http%3A%2F%2Fimg.pconline.com.cn%2Fimages%2Fupload%2Fupc%2Ftx%2Fladyproduct%2F1412%2F03%2Fc0%2F186933_1417582957252.jpg"];
    
    NSURLSession *session=[NSURLSession sharedSession];
    
    NSURLSessionDataTask * task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        //data就是返回的数据。可以进行json等处理
        
        //此处是图片,所以我把图片写入本地
        
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"get.jpg"];

        [data writeToFile:path atomically:YES];
        
        
    }];
    [task resume];
    

NSURLSession GET 使用delegate 请求 实现 NSURLSessionDataDelegate 代理方法

- (void)NSURLSessionDataTaskdelegate {
    NSURLSessionConfiguration *configuration=[NSURLSessionConfiguration defaultSessionConfiguration];
   
    configuration.timeoutIntervalForRequest = 10;
    
    //在蜂窝网络情况下是否继续请求(上传或下载)
    configuration.allowsCellularAccess = NO;
    
    //它会把WiFi和电源可用性考虑在内,建议使用这个,不适用上面的
    configuration.discretionary = YES;

    NSURLSession *session=[NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    
    NSURL *url=[NSURL URLWithString:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1490091307121&di=d9395ca6a2e11cdaa4c6a7d191a7eb43&imgtype=0&src=http%3A%2F%2Fi1.sinaimg.cn%2Fgm%2F2012%2F0529%2FU7233P115DT20120529105050.jpg"];
    
    NSURLSessionDataTask *task = [session dataTaskWithURL:url];
    [task resume];
    
}


- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
    
    //接收响应的时候需要对返回的参数进行处理
    
    NSLog(@"%s",__func__);
    
    //获取总数据长度
    NSLog(@"expectedContentLength   %lld",response.expectedContentLength);
    
    // 允许处理服务器的响应,才会继续接收服务器返回的数据
    completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data {
    NSLog(@"didReceiveData   %lu",(unsigned long)data.length);
    
    
    //在此可以根据上面获得的数据总长度判断是否获取数据完毕,再做其他处理
}


NSURLSession POST 使用block 请求

    NSURL *url=[NSURL URLWithString:@"url"];
    
    NSURLSession *session=[NSURLSession sharedSession];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [@"username=userName&password=123456" dataUsingEncoding:NSUTF8StringEncoding];
    
    
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
    }];
    
    [task resume];

NSURLSession 下载 block

    NSURL *url=[NSURL URLWithString:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1490091074375&di=03327b9db0e521fd5a60c0a1475b76ae&imgtype=0&src=http%3A%2F%2Fimg.pconline.com.cn%2Fimages%2Fupload%2Fupc%2Ftx%2Fladyproduct%2F1412%2F03%2Fc0%2F186933_1417582957252.jpg"];
    
    NSURLSession *session=[NSURLSession sharedSession];
    
    
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        
        // location是沙盒中tmp文件夹下的一个临时url,所以我们需要自己需要把下载的文件移动的需要的地方
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"110.jpg"];
        // 移动文件
        [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:path] error:nil];
        
        NSLog(@"path   %@",path);
        
        
    }];
    
    [downloadTask resume];

NSURLSession 下载 delegate NSURLSessionDownloadDelegate NSURLSessionTaskDelegate

- (void)SessionDownloadTaskURLdelegate {
    NSURLSession *session=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];

    
    NSURL *url=[NSURL URLWithString:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1490091278356&di=44fd6438700a8775d61280d623baa2cf&imgtype=0&src=http%3A%2F%2Fwww.71lady.net%2Fd%2Ffile%2Fyule%2Frihanyule%2Fbagua%2F2015-11-25%2F8d5b965d8f86af711f4ab28b0618c35f.jpg"];

    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];
    
    [task resume];
    
    
    
     
    /*
     断点下载实现方法简述
     */
    
    
    __block NSData *_resumeData = nil; //需将此数据保存到本地
    
    //暂停/取消方法,返回resumeData数据,进行保存,继续下载调用下面的两个任何一个方法,传入保存的resumeData数据,将会自动进行断点下载
    [task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        _resumeData = resumeData;
    }];
    
    
    //继续下载的两个方法
    NSURLSessionDownloadTask *task1=[session downloadTaskWithResumeData:_resumeData completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
    }];
    [task1 resume];
    
    
    //将会调用代理中的 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask   didResumeAtOffset:(int64_t)fileOffset   expectedTotalBytes:(int64_t)expectedTotalBytes; 方法
    NSURLSessionDownloadTask * task2=[session downloadTaskWithResumeData:_resumeData];
    [task2 resume];
}


// 下载完成调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {
    
    // location还是一个临时路径,需要自己挪到需要的路径(此处是caches下面,看要求更改)
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"123.jpg"];
    [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:nil];
}

// 获取 下载进度
- (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);
    
}

//重新下载任务由调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes {
    
}

//NSURLSessionTaskDelegate 下的一个方法

// 由于下载失败导致的下载中断会进入此协议方法,也可以得到用来恢复的数据
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error {
    
    //保存 error.userInfo[NSURLSessionDownloadTaskResumeData] ,下次可以进行断点下载
}


你可能感兴趣的:(iOS-NSURLSession简单使用)