发生错误时调用completionHandler

时间:2018-02-06 23:57:54

标签: swift completionhandler

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

selected_columns = User.__table__.columns
rows = session.query(User).with_entities(*selected_columns).all()
for row in rows :
    print(row._asdict())

1 个答案:

答案 0 :(得分:1)

问题是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