標籤:super ltm sel imp 父類 interface ror arc 允許
NSURLSession *session = [NSURLSession sharedSession];
// 可以不用像connection一樣用代理監聽, 直接會下載檔案, 但是無法獲得下載的進度
NSURLSessionDownloadTask *task = [session
downloadTaskWithURL:[NSURL URLWithString:@""]
completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 檔案儲存體的真實路徑
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
// 剪下location的臨時檔案到真實路徑
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}];
[task resume];
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// 遵搜三種協議 ,但是 最基本的哪一個 協議的繼承性
@interface ViewController ()<NSURLSessionDataDelegate>// 繼承子類就相當於繼承了父類協議
@end
//協議間的繼承關係: <NSURLSessionDataDelegate>:<NSURLSessionTaskDelegate>:<NSURLSessionDelegate>
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// NSURLSession *session = [NSURLSession sharedSession];
// session.delegate = self; // 不能直接設定delegate是 readonly
// 只能一開始的時候建立其代理
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
// 父協議,但是可以傳入子協議:nullable id <NSURLSessionDelegate>
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {}];
[task resume];
}
// 代理方法
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
// 要啟動,否則無法下載
completionHandler(NSURLSessionResponseAllow);// 允許 後再繼續請求數
}
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
}
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
}
iOS 使用NSURLSession下載大檔案