0

I am trying to return the values that i get from the JSON response

    func getAsset(imageId: String) -> String{
    let url = "https://myimage.com"
    Alamofire.request(.GET, url).responseJSON { response in
        switch response.result {
        case .Success:
            if let value = response.result.value {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
                    let json = JSON(value)
                    let singleAsset = json["fields"]["file"]["url"].string
                    print(singleAsset)
                }
            }
        case .Failure(let error):
            print(error)
        }
    }
}

I am trying to return the value (singleAsset) but cant because i keep getting the error unresolved identifier. Ive been trying all night but cant return to value.

2 Answers 2

1

You should use completion handlers:
See: https://thatthinginswift.com/completion-handlers/

func getAsset(imageId: String, completion: (String) -> Void) {
    let url = "https://myimage.com"
    Alamofire.request(.GET, url).responseJSON { response in
        switch response.result {
        case .Success:
            if let value = response.result.value {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
                    let json = JSON(value)
                    let singleAsset = json["fields"]["file"]["url"].string
                    print(singleAsset)
                    completion(singleAsset)
                }
            }
        case .Failure(let error):
            print(error)
            completion(nil);
        }
    }

Usage:

getAsset(imageId) {result in
    println("got back: \(result)")
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks this works but how do i take the value i got out the function? I want to use the output somewhere else in the code not just the function
So i want the value of results to be used elsewhere in the code.
Keep that in a property
0

Whenever you send a request to any web API endpoint, the response is never instantaneous and may take some time. That is why you're actually passing a block of code to Alamofire.request that is run whenever a response is received.

You could also pass a block as a parameter to getAsset function and execute it whenever the response is received (as pointed out by @arturdev already in his answer)

Additionally, you could also have a singleton class and implement a delegate/protocol structure that notifies your view controllers whenever there is a response.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.