嗨,我有一个初学者问题,我在 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
}