iOS中的网络编程-NSURLSession(三)

NSURLSession(iOS7)

  • 使用NSURLSession对象创建Task,然后执行Task
  • Task的类型
    这里写图片描述

Task请求

  • GET
 NSURL *url = [NSURL URLWithString:@"http://localhost:3000/ping"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    //1、获取session对象
    NSURLSession *session = [NSURLSession sharedSession];

    //2、创建任务(可以设置请求头等)
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];


    //    普通get(不可以设置请求头)
    //    NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    //        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    //    }];


    //3、启动任务
    [task resume];
  • POST
 //1、获取session对象
    NSURLSession *session = [NSURLSession sharedSession];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:3000/upload"]];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [@"ss" dataUsingEncoding:NSUTF8StringEncoding];


    //2、创建任务(可以设置请求头等)
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];

    //3、启动任务
    [task resume];
  • Task通过代理实现
//1、获取session对象
    /*
     Configuration:可以做一些配置如超时等等..
     delegate:遵守NSURLSessionDataDelegate协议
     delegateQueue:代理方法回调所在的线程
     */
    NSURLSession  *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
    //2、创建任务
    NSURLSessionTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:3000/download"]]];

    //3、启动任务
    [task resume];
    ---------

#pragma mark- 接收服务器响应<NSURLSessionDataDelegate>
- (void)URLSession:(NSURLSession *)session dataTask:(nonnull NSURLSessionDataTask *)dataTask didReceiveResponse:(nonnull NSURLResponse *)response completionHandler:(nonnull void (^)(NSURLSessionResponseDisposition))completionHandler{
    NSLog(@"%s",__func__);
    /*
     此方法中需要调用completionHandler,传入一个枚举值(默认是取消的),可用于判读respose信息是否正确,若正确,可以继续接收数据,错误,则直接取消
     NSURLSessionResponseCancel:取消处理服务器的响应,接收服务器数据的代理方法将不执行(类似调用[task cancel])
     NSURLSessionResponseAllow:允许处理服务器的响应,才会继续接收服务器的返回的数据
     */
    completionHandler(NSURLSessionResponseAllow);
}
#pragma mark- NSURLSessionDataDelegate接收服务器数据
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
    NSLog(@"%s",__func__);
}

#pragma mark- NSURLSessionDataDelegate请求成功或失败
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    NSLog(@"%s",__func__);
}
  • 文件下载(不可获取下载进度)
//1、获取session对象(下载过程内存不会增长,因为他会存储在临时文件夹下,这个弊端是拿不到下载进度)
    NSURLSession *session = [NSURLSession sharedSession];
    //2、创建任务
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://localhost:3000/download"] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {


        //location:系统会自动将下载好的文件放置到临时的文件夹下,所以我们将文件转移到真正的缓存文件夹下
        NSLog(@"下载完毕\n%@",location);

        NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"demo.mp3"];
        NSLog(@"真实路径\n%@",file);
        //剪切location的临时文件到真实路径
        [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];

    }];
    //3、启动任务
    [task resume];
  • 文件下载(可获取下载进度)
//1、获取session对象
    /*
     Configuration:可以做一些配置如超时等等..
     delegate:遵守NSURLSessionDataDelegate协议
     delegateQueue:代理方法回调所在的线程
     */
    NSURLSession  *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
    //2、创建任务
    NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://localhost:3000/download"]];
    //3、启动任务
    [task resume];
    --------
#pragma mark- 接收服务器响应<NSURLSessionDownloadDelegate>
/*
 //每当服务器返回数据时,就会写入临时文件
 totalBytesExpectedToWrite:总大小
 totalBytesWritten:已经写入多少
 bytesWritten:每次写入多少
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    NSLog(@"%.2f",1.0 * totalBytesWritten / totalBytesExpectedToWrite);
}


#pragma mark- NSURLSessionDownloadDelegate下载完成
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    //location:系统会自动将下载好的文件放置到临时的文件夹下,所以我们将文件转移到真正的缓存文件夹下
    NSLog(@"下载完毕\n%@",location);
    NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"demo.mp3"];
    NSLog(@"真实路径\n%@",file);
    //剪切location的临时文件到真实路径
    [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}

猜你喜欢

转载自blog.csdn.net/hejiasu/article/details/80776325
今日推荐