ios - NSURLSession gets the data properly, but returns nothing after Task.resume() -
this question has answer here:
i trying connect http server data in json format. connects , gets data properly. able print data before task.resume() but, doesn't print after task.resume() also, function returns empty object.
i tried saving global variable before task.resume(). so, can use getter method data, still returns empty.
can please tell me doing wrong here. in advance
func getticketinfo(rdate: string, rname: string) -> nsdictionary { var obj = nsdictionary() let request = nsmutableurlrequest(url: nsurl(string: self.host)!) request.httpmethod = "post" let poststring = "&drivername=\(self.username);&password=\(self.password);&function=getticketprintinvoiceinfo;&routename=\(rname);&routedate=\(rdate);"; request.httpbody = poststring.datausingencoding(nsutf8stringencoding) let task = nsurlsession.sharedsession().datataskwithrequest(request) { data, response, error in if error != nil { print("error=\(error)", terminator: "") return } var parseerror: nserror? let parsedobject: anyobject? { parsedobject = try nsjsonserialization.jsonobjectwithdata(data!, options: nsjsonreadingoptions.allowfragments) } catch let error nserror { parseerror = error parsedobject = nil } catch { fatalerror() } obj = (parsedobject as? nsdictionary)! //prints object fine print(obj) } task.resume() //prints empty result print(obj) return obj; }
because async request. line of code executing outside of block has not gotten results yet. so, won't see anything. if trying debug it. execution order this:
task.resume() //prints empty result print(obj) return obj; then, next execution print(obj) inside. of course, come little bit slow if networking not good.
Comments
Post a Comment