Search code examples
iosswifttwitterclosurestwitter-fabric

How to return value from a Closure in Swift?


So I am using fabric plugin/Twitter-kit to use twitter api in my application. I want to get the image URL of profile picture of a celebrity. here is my code below.

func getImageURL(celebrity :String) -> String{

    var imageURL = ""
    let client = TWTRAPIClient()
    let statusesShowEndpoint = userSearch
    let params = ["q": celebrity,
                  "page" : "1",
                  "count" : "1"
                  ]
    var clientError : NSError?

    let request = client.URLRequestWithMethod("GET", URL: statusesShowEndpoint, parameters: params, error: &clientError)

     client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
        if connectionError != nil {
            print("Error: \(connectionError)")
        }

        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
            print("json: \(json)")

            let profileImageURL: String? = json[0].valueForKey("profile_image_url_https") as? String

            imageURL =  self.cropTheUrlOfImage(profileImageURL!)
            print(imageURL)

            //how do i return the value back. confused ?????
            return imageURL

        } catch let jsonError as NSError {
            print("json error: \(jsonError.localizedDescription)")
        }
    }

    return imageURL

}

I don't know how to return value because the method finishes before the closure executes completely. I am new to swift, Any help is appreciated.

I want to use this method in cellForRowIndexPath in tableview to dowload image from imageURl.


Solution

  • You are correct, sendTwitterRequest will return after your function has already returned, so there is no way for the outer function to return an imageURL.

    Instead, in the closure, take the return value that you want in the cell and store it somewhere (in a member variable) and have the tableView update it itself (e.g. with tableView.reloadData()).

    This will cause it to get the cell again (cellForRow ...). Change the implementation to use the member variable where you stored the value from the call.