Poonam More
Poonam More

Reputation: 799

Swift access data outside closure

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

Upvotes: 3

Views: 1491

Answers (1)

Rob
Rob

Reputation: 437412

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

Upvotes: 8

Related Questions