首先大家要導(dǎo)包兒, 在GitHub上面可以找到
話不多說直接上干貨兒, 具體細節(jié)小編全在代碼中標(biāo)注:
//構(gòu)造資源鏈接
NSString *urlString = @"http://img1.sc115.com/uploads/sc/jpg/HD/1/204.jpg";
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//創(chuàng)建AFN的manager對象
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
//構(gòu)造URL對象
NSURL *url = [NSURL URLWithString:urlString];
//構(gòu)造request對象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//使用系統(tǒng)類創(chuàng)建downLoad Task對象
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(@"%@", downloadProgress);//下載進度
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//返回下載到哪里(返回值是一個路徑)
//拼接存放路徑
NSURL *pathURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
return [pathURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//下載完成走這個block
if (!error)
{
//如果請求沒有錯誤(請求成功), 則打印地址
NSLog(@"%@", filePath);
}
}];
//開始請求
[task resume];