这是我的代码:
func authenticateCredentials(usernameString: String, passwordString: String) -> () -> Bool {
func isAuthUser() -> Bool {
client.invokeAPI("AuthenticateAndFetchData",
body: nil,
httpMethod: "GET",
parameters: ["userid": usernameString,"password":passwordString],
headers: nil)
{
(result, response, error) -> Void in
if let err = error {
print("ERROR ", err)
} else if let res = result {
let jsonArray = res as! NSArray
for value in jsonArray[0] as! NSDictionary {
let jsonstring = value.value as! String
NetworkService.jsonResponse = jsonstring
if let data = jsonstring.data(using: .utf8) {
if let content = try? JSONSerialization.jsonObject(with: data, options: []),
let array = content as? [[String: Any]]
{
for jsondict in array {
let auth = jsondict["IsAuth"]! as! String
self.isAuth = (auth == "true") ? true : false
let substring = NetworkService.parseJSONString(jsonString: jsonstring, key: "Activities")
let substring2 = NetworkService.parseJSONString(jsonString: substring(), key: "activityname")
let activityString = NetworkService.parseJSONvalue(jsonString:substring())
}
}
}
}
}
}
return self.isAuth
}
return isAuthUser
}
}
我在登录按钮上调用此功能。但是当我第一次使用正确的凭据按下按钮时,此函数返回false
,当我再按一次,然后我执行完成处理程序,它将isAuth
更改为true并且函数返回true 。
所以,我必须按两次按钮进行身份验证,我怎样才能让它第一次返回true。我想在函数返回之前等待完成块的执行。
答案 0 :(得分:0)
假设您的客户端调用已经是异步并在主队列上调用其完成处理程序,请将完成处理程序作为额外参数添加到您的方法中:
root
- Users
- [UserID]
- UserPosts
-K_54s1smPPh6qN4znuT
- Posts
- -K_54s1smPPh6qN4znuT
- key1: val
- key2: val
- User:
- -K_54sSomeKeyFromUsersObject: "John Doe"
...
您可以这样称呼它:
func authenticateCredentials(usernameString: String, passwordString: String, completion: @escaping (Bool) -> Void){
client.invokeAPI("AuthenticateAndFetchData",
body: nil,
httpMethod: "GET",
parameters: ["userid": usernameString,"password":passwordString],
headers: nil) {
...
let auth = jsondict["IsAuth"]! as! String
let isAuth = (auth == "true") ? true : false
...
completion(isAuth)
}
}