1

嗨,我有一个初学者问题,我在 Swift 3 中找不到一个好的解决方案。我希望有人能够帮忙。

我有以下代码将检查用户凭据是否有效。我希望它等待请求完成,然后返回真或假。现在它正在异步发送。

此外,我检查 JSON 值的方式的任何改进也将受到欢迎。

func CheckUsernamePassword(username :String ,code:String )-> bool {

    var validCredentials = false


    let urlString = "\(self.baseurl)/accounts/validateusernamepassword.json?username=\(username)&password=\(code)&api_key=\(self.api_key)"

    let url = URL(string: urlString)
    URLSession.shared.dataTask(with:url!) { (data, response, error) in
        if error != nil {
            print("Error URLSession : \(error!)")
            validCredentials = false
        } else {
            do {
                let parsedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]

                if parsedData["validated"] != nil {
                    if "\(parsedData["validated"]!)" == "1" {
                        print("Login credentials are correct")
                        validCredentials = true             
                    }else {
                        print("Login credentials are not correct")
                        print("\(parsedData["validated"]!)")
                        print("\(parsedData["message"]!)")
                        validCredentials = false
                    }
                }else{
                    print("Json Parse error: \(parsedData)")
                    validCredentials = false
                }
            } catch let error as NSError {
                print("Error Parsing Json \(error)" )
                validCredentials = false
            }
        }

        }.resume()
    return validCredentials          
}
4

1 回答 1

7

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

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

  • 将方法的签名(名称应该以小写字母开头)替换为

    func checkUsernamePassword(username: String, code: String, completion: @escaping (Bool)->() ) {
    
  • 删除行var validCredentials = falsereturn validCredentials

  • 替换所有出现的validCredentials = falsewith completion(false)validCredentials = truewith completion(true)

  • 调用方法

    checkUsernamePassword(username: "Foo", code: "Baz") { isValid in
        print(isValid)
        // do something with the returned Bool
        DispatchQueue.main.async {
           // update UI
        }
    }
    
于 2017-03-15T08:31:28.413 回答