ios - Swift Long Polling -
i trying connect url , receive updates it, continuously returns new data in method called http long polling. have found example http long polling in swift isn't working. data returned once doesn't continuously return, , works in curl. here code:
public class longpollingrequest: nsobject { var globaluserinitiatedqueue: dispatch_queue_t { return dispatch_get_global_queue(int(qos_class_user_initiated.rawvalue), 0) } var globalbackgroundqueue: dispatch_queue_t { return dispatch_get_global_queue(int(qos_class_background.rawvalue), 0) } weak var longpolldelegate: longpollingdelegate? var request: nsmutableurlrequest? init(delegate:longpollingdelegate){ longpolldelegate = delegate } public func poll(username: string!, token: string!, vehicleid: string!){ let loginstring = nsstring(format: "%@:%@", username, token) let logindata: nsdata = loginstring.datausingencoding(nsutf8stringencoding)! let base64loginstring = logindata.base64encodedstringwithoptions([]) // create request let url = nsurl(string:"https://streaming.vn.teslamotors.com/stream/\(vehicleid)/?values=speed,odometer,soc,elevation,est_heading,est_lat,est_lng,power,shift_state")! request = nsmutableurlrequest(url: url) request!.httpmethod = "get" request!.setvalue("text/json", forhttpheaderfield: "content-type") request!.setvalue("basic \(base64loginstring)", forhttpheaderfield: "authorization") poll() } private func poll(){ dispatch_async(globalbackgroundqueue) { self.longpoll() } } private func longpoll() -> void{ autoreleasepool{ do{ print("starting request: \(request?.httpbody)") let urlsession = nsurlsession.sharedsession() let datatask = urlsession.datataskwithrequest(self.request!, completionhandler: { (data: nsdata?, response: nsurlresponse?, error: nserror?) -> void in if( error == nil ) { self.longpolldelegate?.datarecieved(data) self.poll() } else { self.longpolldelegate?.errorrecieved(error) } }) datatask.resume() } } }
Comments
Post a Comment