3

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
       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

TechSavy
  • 797
  • 2
  • 8
  • 22

1 Answers1

8

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
Rob
  • 415,655
  • 72
  • 787
  • 1,044