SJURLSessionOperation
基于指定的请求和下载位置创建并管理一个 NSURLSessionDownloadTask
对象。SJURLSessionOperation
是 NSOperation
的子类,可以与 NSOperationQueue 一同使用。此外,它使用 AFURLSessionManager
因此需要 AFNetworking。
截至 Xcode 7,Apple 正式弃用了 NSURLConnection
API。虽然 API 仍将继续工作,但不会添加新功能,Apple 建议所有基于网络的功能今后都利用 NSURLSession。此类的主要目的是使迁移到新的 NSURLSession API 更加容易。本类是为那些大量依赖 AFURLConnectionOperation
中 NSOperation
方面的应用程序设计的。
导入 SJURLSessionOperation
#import "SJURLSessionOperation.h"
实例化 SJURLSessionOperation
NSURL *url = [NSURL URLWithString:@"https://www.example.com/bigfile1.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
SJURLSessionOperation *operation = [[SJURLSessionOperation alloc]initWithRequest:request targetLocation:[NSURL fileURLWithPath:@"~/Desktop/bigfile1.zip"]];
提示:您可以使用之前失败的操作的暂停数据。通过设置暂停数据,操作将从先前的操作失败的地方开始。
SJURLSessionOperation *operation = [[SJURLSessionOperation alloc]initWithRequest:request targetLocation:[NSURL fileURLWithPath:@"~/Desktop/bigfile1.zip"] resumeData:failedOperation.operationResumeData];
开始操作
[operation start];
//Pauses the execution of the operation.
//Pausing a finished, cancelled, or paused operation has no effect.
[operation pause];
/**
* Resumes the execution of the paused operation.
Resuming a operation that is not paused has no effect.
*/
[operation resume];
[operation setDownloadCompletionBlock:^(SJURLSessionOperation * _Nullable operation, NSError * _Nullable error, NSURL * _Nullable fileURL, NSURLResponse * _Nullable response) {
if (error) {
//Handler error
}else{
//Operation finished successfully
}
}];
[operation setDownloadProgressBlock:^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
NSInteger percentage = (double)totalBytesWritten * 100 / (double)totalBytesExpectedToWrite;
}];
NSURL *url = [NSURL URLWithString:@"https://www.example.com/bigfile1.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
SJURLSessionOperation *operation = [[SJURLSessionOperation alloc]initWithRequest:request targetLocation:[NSURL fileURLWithPath:@"~/Desktop/bigfile1.zip"]];
NSURL *url2 = [NSURL URLWithString:@"https://www.example.com/bigfile2.zip"];
NSURLRequest *request2 = [NSURLRequest requestWithURL:url2];
SJURLSessionOperation *operation2 = [[SJURLSessionOperation alloc]initWithRequest:request2 targetLocation:[NSURL fileURLWithPath:@"~/Desktop/bigfile2.zip"]];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 1; //limit it to one operation at a time
//Add opertations
[queue addOperation:operation];
[queue addOperation:operation2];
SJURLSessionOperation 中大量源代码灵感来源于 AFNetworking
Soneé John
SJURLSessionOperation 在 MIT 许可下可用。有关更多信息,请参阅 LICENSE 文件。