NSURLSession實現下載(代理),nsurlsession實現
NSURLSession實現下載(代理)
- (void)downloadTask2
{
{
NSURLSessionConfiguration *cfg = [NSURLSessionConfigurationdefaultSessionConfiguration];
// 1.得到session對象
NSURLSession *session = [NSURLSessionsessionWithConfiguration:cfgdelegate:selfdelegateQueue:[NSOperationQueuemainQueue]];
// 2.建立一個下載task
NSURL *url = [NSURLURLWithString:@"http://localhost:8080/MJServer/resources/test.mp4"];
// NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
// NSLog(@"%@",location);
// }];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];
// 3.開始任務
[task resume];
// 如果給下載任務設定了completionHandler這個block,也實現了下載的代理方法,優先執行block
}
注意:NSURLSessionDownloadTask下載完成之後,將資料儲存在沙箱裡面的tmp臨時檔案中,需要將臨時檔案將臨時檔案剪下或者複製Caches檔案夾。
#pragma mark - NSURLSessionDownloadDelegate
/**
* 下載完畢後調用
*
* @param location 臨時檔案的路徑(下載好的檔案)
*/
- (void)URLSession:(NSURLSession*)session downloadTask:(NSURLSessionDownloadTask*)downloadTask didFinishDownloadingToURL:(NSURL*)location
{
// location : 臨時檔案的路徑(下載好的檔案)
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) lastObject];
// response.suggestedFilename : 建議使用的檔案名稱,一般跟伺服器端的檔案名稱一致
NSString *file = [cachesstringByAppendingPathComponent:downloadTask.response.suggestedFilename];
// 將臨時檔案剪下或者複製Caches檔案夾
NSFileManager *mgr = [NSFileManagerdefaultManager];
// AtPath : 剪下前的檔案路徑
// ToPath : 剪下後的檔案路徑
[mgr moveItemAtPath:location.pathtoPath:fileerror:nil];
}
/**
* 恢複下載時調用
*/
- (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
{
double progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
NSLog(@"下載進度---%f", progress);
}