如何使用Swift在这个Alamofire函数中返回true / false?

时间:2022-12-04 20:14:48
func checkIfFriend()->Bool{

    request(.POST, "", parameters:["":""]).responseJSON{_,_,jsonData in

       if something{ 
return true}
else{
return false
  }      
}

It appears that "return true/false" has to be in the same level than function is and not inside another function (in this case the Alamofire one).

似乎“返回true / false”必须与函数处于同一级别,而不是在另一个函数内(在本例中为Alamofire)。

In that case, how can I return bool in checkIfFriend function depending on what the request return?

在这种情况下,我如何在checkIfFriend函数中返回bool,具体取决于请求返回的内容?

1 个解决方案

#1


0  

Your checkIfFriend() function does not run on the same thread as your Alamofire request (Which runs asynchronously). You should use a callback function/ completion handler as shown below:

您的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.

        })

}

#1


0  

Your checkIfFriend() function does not run on the same thread as your Alamofire request (Which runs asynchronously). You should use a callback function/ completion handler as shown below:

您的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.

        })

}