当我从alamofire获取数据时,它尚未完全加载,在此之前我的下面的代码正在执行,我不知道如何在其中使用完成处理程序,我是iOS编程的新手,任何人请帮忙。
func mobileVerification(mobileNumber:String)->Bool{
let params:[String:String] = ["mobile_num":mobileNumber]
Alamofire.request("*************",method:.post,parameters:params,encoding: URLEncoding.httpBody).responseJSON { response in
var loginMessage = ""
if let jdata = response.data, let utf8Text = String(data: jdata, encoding: .utf8) {
let json = JSON(data:jdata)
print(json)
let array = json["result"].arrayValue
print(array[0]["message"])
if let loginMessage = array[0]["message"].string{
self.view.makeToast(loginMessage)
}
}
}
if loginMessage == "success"
{
//performSegue(withIdentifier: "reg2mobileverification", sender: nil)
return true
}
else
{
self.view.makeToast("LoginFailed")
//print("login Failed")
return false
}
}
答案 0 :(得分:2)
这是异步请求,只能使用完成块方法(闭包)重新运行。 您可以尝试返回true或false,希望这会对您有所帮助。
func mobileVerification(mobileNumber:String,completion:@escaping(Bool) -> Void) {
let params:[String:String] = ["mobile_num":mobileNumber]
Alamofire.request("*************",method:.post,parameters:params,encoding: URLEncoding.httpBody).responseJSON { response in
if let jdata = response.data, let utf8Text = String(data: jdata, encoding: .utf8) {
let json = JSON(data:jdata)
print(json)
let array = json["result"].arrayValue
print(array[0]["message"])
if let loginMessage = array[0]["message"].string{
if loginMessage == "success"
{
self.view.makeToast(loginMessage)
completion(true)
}
else
{
self.view.makeToast("LoginFailed")
completion(false)
}
}
}
}
}
使用Clouser: -
mobileVerification(mobileNumber: "1234567890") { (result) in
if result {
performSegue(withIdentifier: "reg2mobileverification", sender: nil)
}
}
答案 1 :(得分:0)
您必须处理在Alamofire方法中实现的闭包数据:
Alamofire.request("*************",method:.post,parameters:params,encoding: URLEncoding.httpBody).responseJSON { response in
var loginMessage = ""
if let jdata = response.data, let utf8Text = String(data: jdata, encoding: .utf8) {
// IN THIS BLOCK YOU HAVE TO PROCESS RECEIVED DATA AND IMPLEMENT BUSINESS LOGIC
let json = JSON(data:jdata)
print(json)
let array = json["result"].arrayValue
print(array[0]["message"])
if let loginMessage = array[0]["message"].string{
self.view.makeToast(loginMessage)
}
}
}
当收到数据时,此闭包将以异步方式执行。