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

首頁 > 系統 > iOS > 正文

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

2020-07-26 02:33:19
字體:
來源:轉載
供稿:網友

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

#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

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 连江县| 综艺| 陇南市| 宁远县| 西丰县| 德清县| 柯坪县| 垫江县| 安义县| 青海省| 兰西县| 邵武市| 常德市| 绥江县| 定边县| 鲜城| 连平县| 科技| 太康县| 乌兰浩特市| 清丰县| 淮阳县| 乳源| 沙坪坝区| 靖安县| 阿合奇县| 卢氏县| 拉萨市| 石楼县| 罗山县| 达州市| 浙江省| 泸溪县| 神木县| 达孜县| 松阳县| 利津县| 邯郸县| 田东县| 玉田县| 吴桥县|