国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > iOS > 正文

iOS NSURLSessionDownloadTask設置代理文件下載的示例

2019-10-21 18:42:30
字體:
來源:轉載
供稿:網友

通過設置代理我們可以拿到下載進度,對于大文件,我們還需要做到開始、暫停、繼續以及取消等相應操作,這篇文章先簡單的介紹一下通過代理來實現文件下載的問題:

#import "ViewController.h"@interface ViewController ()<NSURLSessionDownloadDelegate>@end@implementation ViewController-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{  [self delegate];}-(void)delegate{  //1.url  NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_03.png"];    //2.創建請求對象  NSURLRequest *request = [NSURLRequest requestWithURL:url];    //3.創建session :注意代理為NSURLSessionDownloadDelegate  NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];    //4.創建Task  NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request];    //5.執行Task  [downloadTask resume];}#pragma mark ----------------------#pragma mark NSURLSessionDownloadDelegate/** * 寫數據 * * @param session          會話對象 * @param downloadTask       下載任務 * @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{  //1. 獲得文件的下載進度  NSLog(@"%f",1.0 * totalBytesWritten/totalBytesExpectedToWrite);}/** * 當恢復下載的時候調用該方法 * * @param fileOffset     從什么地方下載 * @param expectedTotalBytes 文件的總大小 */-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{  NSLog(@"%s",__func__);}/** * 當下載完成的時候調用 * * @param location   文件的臨時存儲路徑 */-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{  NSLog(@"%@",location);    //1 拼接文件全路徑  NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];    //2 剪切文件  [[NSFileManager defaultManager]moveItemAtURL:location toURL:[NSURL fileURLWithPath:fullPath] error:nil];  NSLog(@"%@",fullPath);}/** * 請求結束 */-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{  NSLog(@"didCompleteWithError");}@end

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到IOS開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 响水县| 稻城县| 怀集县| 富民县| 壤塘县| 丰都县| 古交市| 九江市| 大名县| 平原县| 鹤庆县| 任丘市| 平谷区| 洪江市| 安宁市| 珠海市| 板桥市| 黑龙江省| 泰顺县| 胶南市| 清水河县| 龙岩市| 辉南县| 平谷区| 龙南县| 和硕县| 五河县| 湖北省| 宣武区| 宁陵县| 宽甸| 漳平市| 正蓝旗| 张家川| 太原市| 胶南市| 晴隆县| 丹东市| 理塘县| 蓬安县| 黎城县|