ios - JSON parsing and returning data in Swift -


i have swift code retrieving , parsing json data web. seems work fine except 1 problem facing right now. tried solve time, have check sources online.

i have created global dictionary "dicofneighbours" return result of parse other class calling "func startconnection".

dicofneighbours stores parsed data till goes out of closing bracket of the: "let task = session.datataskwithrequest(urlrequest) { ... }" after stores nil. , returned result nil well.

i have tried pass "dicofneighbours" variable reference using inout , still returns nil result.

there might solution missed. appreciate , suggestions.

thanks!

    var dicofneighbours = dictionary<string, [int]>()          func startconnection() -> dictionary<string, [int]>{                 let requesturl: nsurl = nsurl(string: "http://www....data.json")!                 let urlrequest: nsmutableurlrequest = nsmutableurlrequest(url: requesturl)                 let session = nsurlsession.sharedsession()                 let task = session.datataskwithrequest(urlrequest) {                     (data, response, error) -> void in                      let httpresponse = response as! nshttpurlresponse                     let statuscode = httpresponse.statuscode                      if (statuscode == 200) {                          do{                              let json = try nsjsonserialization.jsonobjectwithdata(data!, options:.allowfragments)                              if let neighbours = json["neighbours"] as? [string: array<int>] {                                     var = 0                                     (index, value) in neighbours {                                         self.dicofneighbours[index] = value                                  }                              }                          }catch {                             print("error json: \(error)")                          }                                    }                 }                 task.resume() return self.dicofneighbours             } 

you using return instead of using callback. doing parsing when network connection done; asynchronously.

to synchronize it, you'd need use semaphores, highly discouraged on main thread.

instead, appropriate things result when completion block executed. think of data task 'do stuff, come me when you're done'.


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -