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
}
}
}
Asked
Active
Viewed 867 times
2
-
1You are inside a closure ,whose return type is Void, so you cant return the Bool from inside it – 3stud1ant3 Aug 23 '17 at 04:00
-
aw!! i missed it! thanks for that! :) – Creign Aug 23 '17 at 04:08
2 Answers
2
If you are calling an async method like Alamofire.request
, then you need notify when this async method is over with closures
Try with this
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)
}
}
}
Use it
self.postUser(username: "your UserName", pass: "Your Pass") { (result) in
if(result){
debugPrint("All is fine")
}else{
debugPrint("All is wrong")
}
}

Reinier Melian
- 20,519
- 3
- 38
- 55
-
from that, what is the syntax for calling that function? newbie here :( – Creign Aug 23 '17 at 04:17
-
-
1
You should not return true or false from this method, since this the asynchronous network call, simply use call backs to get your data outside
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
}

3stud1ant3
- 3,586
- 2
- 12
- 15