gpt4 book ai didi

ios - URLSession 委托(delegate)方法不起作用

转载 作者:行者123 更新时间:2023-11-28 07:52:00 25 4
gpt4 key购买 nike

我要从 API 读取文件,但它的大小等于 1.6mb,而且需要很长时间。我希望分部分阅读它,当我找到我需要的数据时,我将停止接收数据。我尝试使用一些委托(delegate)方法,但它们不起作用。我不明白哪里出了问题?
我有下一个代码:

class ViewController: UIViewController, URLSessionTaskDelegate, URLSessionDelegate, URLSessionDataDelegate {

var httpString = "hided"

override func viewDidLoad() {
super.viewDidLoad()
getLogBinData()
}

func getLogBinData() {
let session = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue.main)
if let url = URL(string: httpString + "log.bin") {
var request = URLRequest(url: url)
request.httpMethod = "GET"
let task = session.dataTask(with: request)
task.resume()
}
}

func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
print()
}

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if dataTask.countOfBytesReceived >= 500 {
print(dataTask.countOfBytesReceived)
}
}

func urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
if dataTask.countOfBytesReceived >= 500 {
print(dataTask.countOfBytesReceived)
}
}


}

最佳答案

根据评论,我编辑了代码并且成功了。

class ViewController: UIViewController, URLSessionTaskDelegate, URLSessionDelegate, URLSessionDataDelegate {

var httpString = "hided"

override func viewDidLoad() {
super.viewDidLoad()
getLogBinData()
}

func getLogBinData() {
let session = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue.main)
if let url = URL(string: httpString + "log.bin") {
var request = URLRequest(url: url)
request.httpMethod = "GET"
let task = session.dataTask(with: request)
task.resume()
}
}

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if dataTask.countOfBytesReceived >= 500 {
print(dataTask.countOfBytesReceived)
}
}
}

关于ios - URLSession 委托(delegate)方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49403166/

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