且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在从Swift 3中的函数返回结果之前等待URLSession完成

更新时间:2022-12-29 18:09:45

您不能将异步任务中的某些内容作为返回值返回。

You cannot return something from an asynchronous task as a return value.

不要等待,请使用完成处理程序:

Do not wait, use a completion handler:


  • Replace the signature of the method (the name is supposed to start with a lowercase letter) with

func checkUsernamePassword(username: String, code: String, completion: @escaping (Bool)->() ) {


  • 删除行 var validCredentials = false return validCredentials

    validCredentials = false >完成(错误)和
    validCredentials = true 完成(true)

    Replace all occurrences of validCredentials = false with completion(false) and validCredentials = true with completion(true).

    调用方法

    checkUsernamePassword(username: "Foo", code: "Baz") { isValid in
        print(isValid)
        // do something with the returned Bool
        DispatchQueue.main.async {
           // update UI
        }
    }