I am newbie to iOS. I have query that how can we access data or variables inside closure. Following is my code snippet.
self.fetchData() { data in
dis
You should employ completion handler closure in the function that calls fetchData
, e.g.:
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'd call it like so:
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