gpt4 book ai didi

Swift:无法在委托(delegate)中获取 URLSession 下载的进度?

转载 作者:行者123 更新时间:2023-11-30 12:20:26 27 4
gpt4 key购买 nike

好吧,我以前从未保存过文件(在本例中为 m4as),并且不知道我是否正确执行此操作,而且无法获取 URL 的下载进度,尽管此处包含所需的 URLSessionDownloadDelegate 函数:

 func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if totalBytesExpectedToWrite > 0 {
let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
print("Progress \(downloadTask) \(progress)")
}
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print("Download finished: \(location)")
try? FileManager.default.removeItem(at: location)
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
print("Task completed: \(task), error: \(error)")
}

我从教程中得到了这些,但是没有任何内容打印到控制台。我尝试调用这些函数,但我不知道从哪里获取 downloadTask var 或 session 。

这就是我下载文件的方式,效果如下:

func goDownload()
{
if let audioUrl = testUrl { //set at beginning

// then lets create your document folder url
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

// lets create your destination file url
let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
print(destinationUrl)

// to check if it exists before downloading it
if FileManager.default.fileExists(atPath: destinationUrl.path) {
print("********** The file already exists at path")

// if the file doesn't exist
} else {
// you can use NSURLSession.sharedSession to download the data asynchronously
URLSession.shared.downloadTask(with: audioUrl, completionHandler: { (location, response, error) -> Void in
guard let location = location, error == nil else { return }
do {
// after downloading your file you need to move it to your destination url
try FileManager.default.moveItem(at: location, to: destinationUrl)

//success
print("************** SUCCESS File moved to documents folder", audioUrl)
self.playModeStreaming = false

self.pausePlay()
AudioPlayerManager.shared.play(url: audioUrl)

} catch let error as NSError {
print(error.localizedDescription)
}
}).resume()
}
}
}

但是,即使我尝试从这里获取 downloadTask,我也会遇到类型问题。如何使用此下载函数获取下载进度(收到的字节数等)?

编辑:这就是我所拥有的:

 var session = URLSession()
let sessDelegate = CustomDelegate()
self.session = URLSession(configuration: .default, delegate: sessDelegate, delegateQueue: nil)

然后将上述函数中的 URLSession.shared 替换为 session

我的自定义委托(delegate)类分别:

class CustomDelegate : NSObject, URLSessionDataDelegate, URLSessionTaskDelegate {

//define all `NSURLSessionDataDelegate` and `NSURLSessionTaskDelegate` methods here
//URLSessionDelegate methods

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if totalBytesExpectedToWrite > 0 {
let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
print("Progress \(downloadTask) \(progress)")
}
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print("Download finished: \(location)")
try? FileManager.default.removeItem(at: location)
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
print("Task completed: \(task), error: \(error)")
}

}

最佳答案

您可以添加自定义委托(delegate)类,并实现 NSURLSessionDataDelegateNSURLSessionTaskDelegate 协议(protocol)。

class CustomDelegate : NSObject, NSURLSessionDataDelegate, NSURLSessionTaskDelegate {

//define all `NSURLSessionDataDelegate` and `NSURLSessionTaskDelegate` methods here

}

现在创建上述类的实例,如下所示:

let myCustomDelegate = CustomDelegate();

然后,您需要设置 NSURLSession 实例的委托(delegate)属性,如下所示:

objective-c

NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:myCustomDelegate delegateQueue:nil];

SWIFT 3

let session = URLSession(configuration: .default, delegate: myCustomDelegate, delegateQueue: nil)

引用链接:

  1. NSURLSession Class Reference
  2. From NSURLConnection to NSURLSession

关于Swift:无法在委托(delegate)中获取 URLSession 下载的进度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44855537/

27 4 0
文章推荐: javascript - 如何多次使用
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com