func postUser(username: String, pass: String) -> Bool {
Alamofire.request("https://someAPI.com/auth/login", method: .post, parameters: ["email": contact, "password": pass], encoding: URLEncoding.default, headers: ["Accept":"application/json"]).responseJSON { (response) in
switch(response.result) {
case .success(let value):
let json = JSON(value)
print("JSON: \(json)")
print(json["data"]["result"])
return true
case .failure(let error):
print(error)
return false
}
}
}
答案 0 :(得分:2)
如果您正在调用Alamofire.request
之类的异步方法,那么当这个异步方法结束时,您需要通知closures
尝试使用
func postUser(username: String, pass: String, finishedClosured:@escaping ((Bool)->Void)) {
Alamofire.request("https://someAPI.com/auth/login", method: .post, parameters: ["email": contact, "password": pass], encoding: URLEncoding.default, headers: ["Accept":"application/json"]).responseJSON { (response) in
switch(response.result) {
case .success(let value):
let json = JSON(value)
print("JSON: \(json)")
print(json["data"]["result"])
finishedClosured(true)
case .failure(let error):
print(error)
finishedClosured(false)
}
}
}
使用
self.postUser(username: "your UserName", pass: "Your Pass") { (result) in
if(result){
debugPrint("All is fine")
}else{
debugPrint("All is wrong")
}
}
答案 1 :(得分:1)
您不应该从此方法返回true或false,因为这是异步网络调用,只需使用回调来获取您的数据
func postUser(username: String, pass: String callback: @escaping (Bool) -> Void){
Alamofire.request("https://someAPI.com/auth/login", method: .post, parameters: ["email": contact, "password": pass], encoding: URLEncoding.default, headers: ["Accept":"application/json"]).responseJSON { (response) in
switch(response.result) {
case .success(let value):
let json = JSON(value)
print("JSON: \(json)")
print(json["data"]["result"])
callback(true) //using this you can send back the data
case .failure(let error):
print(error)
callback(false)
}
}
//here you can return true or false but I dont think you should
}