NSURLSessionDownloadTask

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"I'm Hear");
    //1 創(chuàng)建URL回話配置
    NSURLSessionConfiguration *cfg=[NSURLSessionConfiguration defaultSessionConfiguration];
    //2 創(chuàng)建帶配置的URL會(huì)話
    NSURLSession *session=[NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    //3 創(chuàng)建下載任務(wù)/Users/smartlei/Sites/頭像.jpg
    NSURL *url=[NSURL URLWithString:@"http://127.0.0.1/Xcode_7.0.1.dmg"];
//    NSURLRequest *request=[NSURLRequest requestWithURL:url];
//    NSURLSessionDownloadTask *task=[session downloadTaskWithRequest:request];
    NSURLSessionDownloadTask *task=[session downloadTaskWithURL:url];
    
    //4 開啟任務(wù)
    [task resume];
}
#pragma NSURLSessionDownloadDelegate
//下載完成
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    //下載完成后系統(tǒng)會(huì)在沙盒中保存?zhèn)€臨時(shí)文件,如果不保存執(zhí)行完沙盒自動(dòng)清除
    [[NSFileManager defaultManager] copyItemAtPath:location.path toPath:@"/Users/smartlei/Desktop/qq.dmg" error:NULL];
}
//監(jiān)聽下載進(jìn)度的方法
//bytesWritten:本次寫入了多少字節(jié)
//totalBytesWritten:總共寫入多少字節(jié)
//totalBytesExpectedToWrite:期望一共寫入多少字節(jié)
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    
    CGFloat progress=(float)totalBytesWritten/totalBytesExpectedToWrite;
     NSLog(@"下載進(jìn)度:%lf,線程:%@",progress,[NSThread currentThread]);
    dispatch_async(dispatch_get_main_queue(), ^{
        //主隊(duì)列中更新進(jìn)度
        self.progressView.progress=progress;
    });
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
    
}


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容