NSURLSession

  • 使用步骤

    • 使用NSURLSession创建Task,然后执行Task
  • Task类型

  • NSURLSessionTask是一个抽象类
    • NSURLSessionDataTask:(用来接收服务器数据,也可用于下载)
      • NSURLSessionUploadTask
    • NSURLSessionDownloadTask

事例程序1

必须创建任务,然后启动任务(直接发送一个URL ,是一个get请求),需要设置请求头的时候才需要建立NSURLRequest请求

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 获得URLSession对象
    NSURLSession * session = [NSURLSession sharedSession];

    // 创建任务
    NSURLSessionTask * task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"]] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
    }];

    // 启动任务
    [task resume];
}

如果只是一个单纯的get请求,不需要设置NSURLRequest请求

- (void)get2 {
    // 获得URLSession对象
    NSURLSession * session = [NSURLSession sharedSession];

    // 创建任务
    NSURLSessionTask * task = [session dataTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);

    }];
    // 启动任务
    [task resume];
}

使用POST请求

- (void)post {
    // 获得URLSession对象
    NSURLSession * session = [NSURLSession sharedSession];

    // 创建一个请求,必须是可变的请求
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login"]];
    request.HTTPMethod = @"POST";
    // 设置请求体
    request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];

    // 创建任务
    NSURLSessionTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);

    }] ;

    // 启动任务
    [task resume];
}

下载任务

这里不需要担心下载比较大的文件,已经自动集成了下载储存。但是无法监听下载进度

// 下载,好处就是可以直接缓存下载内容,但是无法监听下载进度
- (void)download {
    // 获得NSURLSession对象
    NSURLSession * session = [NSURLSession sharedSession];

    // 获得下载任务:location下载的文件自动存储的路径
    NSURLSessionDownloadTask * task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",location);

        // 文件需要存放的真实路径(response.suggestedFilename为服务器建议文件名)
        NSString * file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];

        // 剪切location的临时文件到真实的文件路径
        NSFileManager * manager = [NSFileManager defaultManager];

        [manager moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
    }];

    [task resume];
}

代理方法接收服务器数据

// data的代理方法
- (void)data {


    // 必须在创建的时候设置代理才可以监听
    // NSURLSessionConfiguration:是一些配置文件
    // delegateQueue:代理执行的线程,创建一个就是默认在子线程执行
    NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];

    // 创建任务
    NSURLSessionDataTask * task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"]]];

    [task resume];
}

#pragma mark - NSURLSessionDataDelegate
/**
 *  1.接收到服务器的响应,当接收到响应的时候会自动判断是否符合我们的要求,接收到服务器的响应之后我们需要手动调用block(completionHandler)来处置请求的响应
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
    // 默认是NSURLSessionResponseCancel
    // NSURLSessionResponseAllow:允许处理服务器的响应,才会处理服务器返回请求
    completionHandler(NSURLSessionResponseAllow);
}


/**
 *  2.接收到服务器的数据(可能会被调用多次)
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {

}



/**
 *  3.请求成功或者失败,如果失败error有值
 */
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {

}

监听下载进度,用代理方法

// 下载:好处就是可以直接写入到一个临时文件,但是有个缺点无法监听下载进度
- (void)download {
    // 获得NSURLSession对象
    NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];


    NSURLSessionDownloadTask * task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];


    [task resume];
}

#pragma mark - NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {

}


/**
 *  断点下载用处
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes {

}

/**
 *  每当写入临时文件的时候,就会调用一次这个方法
*  @param bytesWritten              这次写入的大小
 *  @param totalBytesWritten         已经写入的大小
 *  @param totalBytesExpectedToWrite 总大小
 */
- (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);
}

/**
 *  下载完毕就会调用一次
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSString * file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];

    // 剪切location的临时文件到真实的文件路径
    NSFileManager * manager = [NSFileManager defaultManager];

    [manager moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}

大文件断点下载

这种下载会有一个缺点,就是当前的断点下载只能是程序在当前运行中,一旦层序退出之后文件在内存中就丢失了,下次启动没办法进行断点下载。

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDataDelegate,NSURLSessionDownloadDelegate>
/** 下载任务 */
@property (nonatomic,strong) NSURLSessionDownloadTask * task;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}



/** 开始下载 */
- (IBAction)start:(id)sender {
    [self download];
}
/** 暂停下载 */
- (IBAction)suspend:(id)sender {
    [self.task suspend];
}

/** 恢复下载 */
- (IBAction)resume:(id)sender {
    [self.task resume];
}

// 下载:好处就是可以直接写入到一个临时文件,但是有个缺点无法监听下载进度
- (void)download {
    // 获得NSURLSession对象
    NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];


    NSURLSessionDownloadTask * task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];

    self.task = task;
    [task resume];
}

#pragma mark - NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {

}


/**
 *  断点下载用处
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes {

}

/**
 *  每当写入临时文件的时候,就会调用一次这个方法
*  @param bytesWritten              这次写入的大小
 *  @param totalBytesWritten         已经写入的大小
 *  @param totalBytesExpectedToWrite 总大小
 */
- (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);
}

/**
 *  下载完毕就会调用一次
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSString * file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];

    // 剪切location的临时文件到真实的文件路径
    NSFileManager * manager = [NSFileManager defaultManager];

    [manager moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}


@end

自己实现断点下载

/**
  *  自己实现断点下载,必须设置请求文件的范围:固定格式Range,请求下载的范围:0-1024字节  (1024-)从1024字节往后下载
  */
  [[NSMutableURLRequest requestWithURL:nil] setValue:@"0-1024" forHTTPHeaderField:@"Range"];

断点下载

这里没有写完,有点蛋疼,因为每次退出应用之后,temp文件夹总是被清空,所以需要将临时文件夹中的下载的文件保存,然后下次下载的时候再将它读出来。

#import "ViewController.h"

#define JXResumeDataFile [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"resumeData.tmp"]

@interface ViewController ()<NSURLSessionDataDelegate,NSURLSessionDownloadDelegate>
/** 下载任务 */
@property (nonatomic,strong) NSURLSessionDownloadTask * task;
/** 记录上次下载信息 */
@property (nonatomic,strong) NSData * resumeData;
/** session */
@property (nonatomic,strong) NSURLSession * session;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (NSURLSession *)session{
    if (_session == nil) {
        _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    }
    return _session;
}

- (NSData *)resumeData{
    if (_resumeData == nil) {
        _resumeData = [NSData dataWithContentsOfFile:JXResumeDataFile];
    }
    return _resumeData;
}

/** 开始下载 */
- (IBAction)start:(id)sender {
    [self download];

}
/** 暂停下载 */
- (IBAction)suspend:(id)sender {

    // resumeData:是苹果提供的一个临时的data,记录交互信息,以及上次下载信息等。block是一个临时的block,不会循环引用
    // 一旦这个task已经取消就无法恢复
    [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        self.resumeData = resumeData;

        // 可以将这个data写入沙盒保存起来,下次进入程序就可以将之读进来可以继续下载
        [resumeData writeToFile:JXResumeDataFile atomically:YES];

        // caches文件夹
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

        // 缓存文件
        NSString *tmp = NSTemporaryDirectory();
        NSFileManager *mgr = [NSFileManager defaultManager];
        NSArray *subpaths = [mgr subpathsAtPath:tmp];
        NSString *file = [tmp stringByAppendingPathComponent:[subpaths lastObject]];
        NSString *cachesTempFile = [caches stringByAppendingPathComponent:[file lastPathComponent]];
        [mgr moveItemAtPath:file toPath:cachesTempFile error:nil];

        [@{@"tempFile" : cachesTempFile} writeToFile:[caches stringByAppendingPathComponent:@"tempFile.plist"] atomically:YES];

    }];
}

/** 恢复下载 */
- (IBAction)resume:(id)sender {
    self.task = [self.session downloadTaskWithResumeData:self.resumeData];
    [self.task resume];
}

// 下载:好处就是可以直接写入到一个临时文件,但是有个缺点无法监听下载进度
- (void)download {

    if (self.resumeData) {
        // 获得上次下载任务
        self.task = [self.session downloadTaskWithResumeData:self.resumeData];

    } else {

        self.task = [self.session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
    }

    [self.task resume];
}

#pragma mark - NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {

}


/**
 *  断点下载用处
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes {

}

/**
 *  每当写入临时文件的时候,就会调用一次这个方法
*  @param bytesWritten              这次写入的大小
 *  @param totalBytesWritten         已经写入的大小
 *  @param totalBytesExpectedToWrite 总大小
 */
- (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);
}

/**
 *  下载完毕就会调用一次
 */
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSString * file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];

    // 剪切location的临时文件到真实的文件路径
    NSFileManager * manager = [NSFileManager defaultManager];

    [manager moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];

    //
}


@end
// 当下载失败的时候讲失败的数据保存下来
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    // 保存下载失败的数据
    self.resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
}

上传文件

说好的简单在哪里呢。

#import "ViewController.h"

#define XMGBoundary @"520it"
#define XMGEncode(string) [string dataUsingEncoding:NSUTF8StringEncoding]
#define XMGNewLine [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];


}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSURLSession * session = [NSURLSession sharedSession];

    // 这个方式是用于PUT请求,需要服务器支持(比较危险)
//    [session uploadTaskWithRequest:<#(nonnull NSURLRequest *)#> fromFile:<#(nonnull NSURL *)#>]

    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/upload"]];

    request.HTTPMethod = @"POST";

    // 设置请求头(告诉服务器,这是一个文件上传的请求)
    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", XMGBoundary] forHTTPHeaderField:@"Content-Type"];

    // 设置请求体
    NSMutableData *body = [NSMutableData data];

    // 文件参数
    // 分割线
    [body appendData:XMGEncode(@"--")];
    [body appendData:XMGEncode(XMGBoundary)];
    [body appendData:XMGNewLine];

    // 文件参数名
    [body appendData:XMGEncode([NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"test.png\""])];
    [body appendData:XMGNewLine];

    // 文件的类型
    [body appendData:XMGEncode([NSString stringWithFormat:@"Content-Type: image/png"])];
    [body appendData:XMGNewLine];

    // 文件数据
    [body appendData:XMGNewLine];
    [body appendData:[NSData dataWithContentsOfFile:@"/Users/xiaomage/Desktop/test.png"]];
    [body appendData:XMGNewLine];

    // 结束标记
    /*
     --分割线--\r\n
     */
    [body appendData:XMGEncode(@"--")];
    [body appendData:XMGEncode(XMGBoundary)];
    [body appendData:XMGEncode(@"--")];
    [body appendData:XMGNewLine];

    [[session uploadTaskWithRequest:request fromData:nil completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    }] resume];
}
@end

results matching ""

    No results matching ""