【发布时间】:2017-05-18 04:38:01
【问题描述】:
我有这个函数,它有一个完成块,函数异步返回而不等待完成。
我希望我的函数延迟它的返回,直到它的完成块完成。我更改了回调函数,但它不起作用,我是 swift 新手,所以对 GCD 知之甚少,他们的 API 也发生了很大变化。
func authenticateCredentials(usernameString: String, passwordString: String, completion: @escaping (Bool)-> Void) {
var boolVal: Bool = false
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
// print(jsonArray)
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
print(type(of: auth))
print(auth)
boolVal = (auth == "true") ? true : false
self.isAuth = boolVal
print(boolVal)
completion(boolVal) // callback here
}
}
}
}
}
}
}
我在这样的登录操作中从我的 viewController 调用这个函数。
// After login button is pressed
@IBAction func loginButtonTapped(_ sender: UIButton) {
let userid = userIDtxt.text
let password = userpasswordtxt.text
//Display an alert if no text is entered
if (userid?.isEmpty)! || (password?.isEmpty)! {
displayAlertMessage("Please enter userid/password")
}
// take this userid and password and authenticate from sql server and move to
else {
// Run the spinner to show the task is in progress
print("\(userid)" + " " + "\(password)")
nw.authenticateCredentials(usernameString: userid!, passwordString: password!){
(boolVal) in
self.nw.isAuth = boolVal
}
showActivityIndicatory(uiview: view)
if nw.isAuth == true {
// User authenticated
}
else {
// wrong user
}
}
}
所以这里authenticateCredentials函数预先返回,它返回false,所以当我第一次点击我的登录按钮时,我收到false,当我第二次点击它时,我收到true。我想在第一次点击时接收真实和认证的用户。
【问题讨论】:
-
简短回答:你不能也不应该那样做。您需要了解异步代码和完成处理程序的工作原理。
标签: ios swift asynchronous callback synchronization