gpt4 book ai didi

swift - 发生错误时调用 completionHandler

转载 作者:行者123 更新时间:2023-11-28 15:04:23 27 4
gpt4 key购买 nike

我试图将 bool 值传递给我的完成处理程序。当应用程序运行时,将 bool 传递给我的完成处理程序的结果决定了我显示的警报。如果我在错误检查中调用它,应用程序会崩溃/锁定。如果我在其他任何地方调用它,一切都会按预期进行吗?我迷路了,找不到这个问题的答案。请帮忙。

class func TestConnection(_ urlBase: String, usingCommand command: String, completionHandler: @escaping (Bool) -> Void) {
let urlString = urlBase + "/" + command
var IsValidConnection = false
guard let url = URL(string: urlString) else {
completionHandler(IsValidConnection)
return
}

URLSession.shared.dataTask(with: url) { (data, response, error) in
//App blows up when running this block of code.
//Doesn't return. App crashes/locks up
guard error == nil else {
completionHandler(false)
return
}
//App works as expected when running code below
guard let _: HTTPURLResponse = response as? HTTPURLResponse else {
completionHandler(false)
return
}

let serverResponse = response as! HTTPURLResponse

if serverResponse.statusCode == 200 {
IsValidConnection = true
}

completionHandler(IsValidConnection)

}.resume()
}

最佳答案

问题是 URLSession.shared.dataTask 有自己的名为 completionHandlercompletionHandler。只需将您的处理程序重命名为 testConnectionCompletionHandler:

class func TestConnection(_ urlBase: String, usingCommand command: String, testConnectionCompletionHandler: @escaping (Bool) -> Void) {
let urlString = urlBase + "/" + command
var IsValidConnection = false
guard let url = URL(string: urlString) else {
testConnectionCompletionHandler(IsValidConnection)
return
}

URLSession.shared.dataTask(with: url) { (data, response, error) in
//App blows up when running this block of code.
//Doesn't return. App crashes/locks up
guard error == nil else {
testConnectionCompletionHandler(false)
return
}
//App works as expected when running code below
guard let _: HTTPURLResponse = response as? HTTPURLResponse else {
testConnectionCompletionHandler(false)
return
}

let serverResponse = response as! HTTPURLResponse

if serverResponse.statusCode == 200 {
IsValidConnection = true
}

testConnectionCompletionHandler(IsValidConnection)

}.resume()
}

更多信息:https://developer.apple.com/documentation/foundation/urlsession/1407613-datatask

关于swift - 发生错误时调用 completionHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48653868/

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