Quick access data outside of closing

I am new to iOS. I have a request how can we access data or variables inside a closure. Below is a code snippet.

self.fetchData() { data in
       dispatch_async(dispatch_get_main_queue()) {
            println("Finished request")
            if let data = data { // unwrap your data (!= nil)
            let myResponseStr = NSString(data: data, encoding: NSUTF8StringEncoding) as! String

            }
        }
    }      

      

I want to get myResponseStr outside, like self.myString = myResponseStr

+3


source to share


1 answer


You must use the closure of the completion handler in a function that calls fetchData

, for example:

func fetchString(completionHandler: (String?) -> ()) {
    self.fetchData() { responseData in
        dispatch_async(dispatch_get_main_queue()) {
            println("Finished request")
            if let data = responseData { // unwrap your data (!= nil)
                let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
                completionHandler(responseString)
            } else {
                completionHandler(nil)
            }
        }
    }      
}

      



And you would call it like this:

fetchString() { responseString in
    // use `responseString` here, e.g. update UI and or model here

    self.myString = responseString
}

// but not here, because the above runs asynchronously

      

+8


source







All Articles