func checkIfFriend()->Bool{
request(.POST, "", parameters:["":""]).responseJSON{_,_,jsonData in
if something{
return true}
else{
return false
}
}
似乎“return true / false”必须与函数处于同一级别,而不是在另一个函数内(在本例中为Alamofire)。
在这种情况下,我如何在checkIfFriend函数中返回bool,具体取决于请求返回的内容?
答案 0 :(得分:0)
您的checkIfFriend()函数不会与您的Alamofire请求(异步运行)在同一个线程上运行。您应该使用回调函数/完成处理程序,如下所示:
func checkIfFriend(completion : (Bool, Any?, Error?) -> Void) {
request(.POST, "", parameters:["":""]).responseJSON{_,_,jsonData in
if something{
completion(true, contentFromResponse, nil)
//return true
}else{
completion(false, contentFromResponse, nil)
// return false
}
}
//Then you can call your checkIfFriend Function like shown below and make use
// of the "returned" bool values from the completion Handler
override func viewDidLoad() {
super.viewDidLoad()
var areWeFriends: Bool = Bool()
var responseContent: Any = Any()
checkIfFriend(completion: { (success, content, error) in
areWeFriends = success // are We Friends will equal true or false depending on your response from alamofire.
//You can also use the content of the response any errors if you wish.
})
}