gpt4 book ai didi

swift - 未调用 URLSessionDelegate 方法

转载 作者:行者123 更新时间:2023-11-28 05:36:44 24 4
gpt4 key购买 nike

首先,我已经检查了类似的现有问题,但没有一个答案适用。
NSURLSession delegates not called
URLSessionDelegate Function Not Being Called

我正在尝试使用 URLSessionDownloadTask 下载文件,就像这样

class MyNetworkManager : NSObject
{
static let instance = MyNetworkManager()

var downloadSession : URLSession?

init()
{
super.init()

let downloadConfiguration = URLSessionConfiguration.default
downloadSession = URLSession(configuration: downloadConfiguration, delegate: self, delegateQueue: nil)
}

func download(_ url : URL)
{
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "GET"
let downloadTask = downloadSession?.downloadTask(with: urlRequest)

downloadTask?.resume()
}
}

extension MyNetworkManager : URLSessionDelegate
{
func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
//
}

func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL)
{
//
}

func urlSession(_ session: URLSession,
task: URLSessionTask,
didCompleteWithError error: Error?)
{
//
}
}

但是,没有 URLSessionDelegate 方法被调用。

通常情况下,如果您使用完成处理程序创建任务,则不会调用委托(delegate)方法 - 事实并非如此,我在创建任务时仅使用 URLRequest 作为参数。

Session 的 delegate 已正确设置,调用 downloadTask?.resume() 后,其 state 属性为 running

MyNetworkManager 是单例,我是这样用的

MyNetworkManager.instance.download(someURL)

所以肯定保留了一个实例。

我是不是漏掉了什么?

最佳答案

您必须遵守相关协议(protocol),例如:

extension MyNetworkManager: URLSessionDelegate {
// this is intentionally blank

// obviously, if you implement any delegate methods for this protocol, put them here
}

extension MyNetworkManager: URLSessionDownloadDelegate {
func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {
print(#function)
}

func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
print(#function)
}
}

extension MyNetworkManager: URLSessionTaskDelegate {
func urlSession(_ session: URLSession,
task: URLSessionTask,
didCompleteWithError error: Error?) {
print(#function, error ?? "No error")
}
}

如果你不符合URLSessionDownloadDelegate , 它不会调用 URLSessionDownloadDelegate 方法。

关于swift - 未调用 URLSessionDelegate 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58410910/

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