我试图将 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
有自己的名为 completionHandler
的 completionHandler
。只需将您的处理程序重命名为 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/