简体   繁体   中英

Return a value from a Alamofire closure

i have this function called sendRequest in a class called A and this sendRequest function returns a Any object and in first line i created a variable like this var serverResponse = JSON() and i have this code to request

upload.uploadProgress(closure: { (Progress) in
                })
       upload.responseJSON { response in

       print(response.response?.statusCode as Any)

       if(response.result.isSuccess){
            serverResponse = JSON(response.result.value!)
            print("Success\(serverResponse)")

       }else{
            serverResponse = JSON(response.result.value!)
            print("No Success\(serverResponse)")
       }
  }

the above code is inside the sendRequest function and at the end/outside of this closure i have a return statement returning the server response return serverResponse

and i am accessing this function from class B i created an object of class A now i have this code in class B

var response: Any =  request.sendRequest("url", parameters: body, headers: [:])

now the problem is the response variable here will always have an empty JSON object and i think thats because in the closure the api call is being processed in the background so before the result comes from the server the return statement gets executed giving me an empty JSON object on class B

and i tried returning the serverResponse in the if statement where i checked if its successful or not and gives me an error like this:

Unexpected non-void return value in void function

so how can i solve this problem?

You are correct. It is being returned empty because it is being run on the background thread. When making network requests we therefor tend to use completionBlocks Swift 5 implemented the new typ of Result<Any, Error> which is really convenient.

Try implementing completion((Result<Any, Error>) -> ()) in your function params instead. When you get the response you unwrap it my writing:

switch result {
    case .succeses(let data):
    //Do something
    break
    case .failure(let error):
    //Do something
    break
}

As you are inside the actual block you can't execute a return statement. That's the error you are getting. The block itself doesn't ask for a return. Unlike map, filter, reduce etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM