gpt4 book ai didi

ios - 文件下载器使用 NSURLSessionTask downloadTask

转载 作者:行者123 更新时间:2023-11-29 11:45:50 29 4
gpt4 key购买 nike

我想创建文件下载管理器来下载多个具有下载百分比和播放暂停删除功能的文件。

我尝试使用以下代码成功下载多个文件...但无法添加进度条请帮忙 enter image description here

enter image description here

for (int i = 0; i < [arr_bookChapter count]; i++) {
NSURLSessionTask * downloadTask = [session downloadTaskWithURL: downloadfileUrl completionHandler: ^ (NSURL * location, NSURLResponse * response, NSError * error) {
if (error == nil) {
NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse * ) response;

if ([httpResponse statusCode] == 200) {

//download file save here

dispatch_queue_t backgroundQueue = dispatch_queue_create("dispatch_queue_#1", 0);
dispatch_async(backgroundQueue, ^ {

dispatch_async(dispatch_get_main_queue(), ^ {
// NSError *error;

//download complete here

});
});
}
} else {
//faile
}

}];
[downloadTask resume];
}

在这里我得到了swift code :有人可以为 Objective-C 创建或提供解决方案

最佳答案

你可以很容易地做到这一点,你只需要在你的 ViewContorller 中实现这些委托(delegate)。

<NSURLSessionDataDelegate, NSURLSessionDelegate, NSURLSessionTaskDelegate>

然后您需要遵循以下代码:

@property (nonatomic, retain) NSMutableData *dataToDownload;
@property (nonatomic) float downloadSize;

- (void)viewDidLoad {
[super viewDidLoad];

NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];

NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];

NSURL *url = [NSURL URLWithString: @"your url"];
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithURL: url];

[dataTask resume];
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
completionHandler(NSURLSessionResponseAllow);

progressBar.progress=0.0f;
_downloadSize=[response expectedContentLength];
_dataToDownload=[[NSMutableData alloc]init];
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
[_dataToDownload appendData:data];
progressBar.progress=[ _dataToDownload length ]/_downloadSize;
}

关于ios - 文件下载器使用 NSURLSessionTask downloadTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43976968/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com