【问题标题】:How can I return true/false in this Alamofire function using Swift?如何使用 Swift 在这个 Alamofire 函数中返回真/假?
【发布时间】:2016-06-25 16:41:41
【问题描述】:
func checkIfFriend()->Bool{
request(.POST, "", parameters:["":""]).responseJSON{_,_,jsonData in
if something{
return true}
else{
return false
}
}
似乎“返回真/假”必须与函数处于同一级别,而不是在另一个函数内部(在本例中为 Alamofire 函数)。
在这种情况下,如何根据请求返回的内容在 checkIfFriend 函数中返回 bool?
【问题讨论】:
标签:
ios
swift
return
boolean
alamofire
【解决方案1】:
您的 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.
})
}