swift - String nil inside NSURLSession -


i declare string in beginning

var teststring: string?   let task = nsurlsession.sharedsession().datataskwithurl(url!) {(data, response, error) in      let xml = swxmlhash.parse(data)      teststring =  xml["root"]["schedule"]["date"].element?.text  } 

but outside nsurlsession, teststring nil. how can make not become nil , can use value?

for example, want use

println (teststring)  

after method block. nil

the reason variable nil because closures executed asynchronously. means rest of code after network request continue called normal, code containing parameters data, response , error called when network request finished.

to work around this, try putting whatever trying variable inside closure, println(teststring) inside curly brackets.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -