0

I am trying to connect to a url and then receive updates from it, as it continuously returns new data in a method called HTTP Long Polling. I have found this example HTTP Long Polling in Swift but it simply isn't working. Data is returned once but then doesn't continuously return, and it works in CURL. Here is my 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 the 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()
            }
        }
    }
Community
  • 1
  • 1
Dylan Diamond
  • 161
  • 2
  • 11
  • Try making the dataTask, a member of the class, than the local variable. Also could it be possible for you to provide a sample parameters to use with the poll(...) method? – Shripada Feb 08 '16 at 04:57
  • I'll see if I can get demo credentials. Thanks for the advice, and also do I need to call `self.poll()` after data is received or will it continue to fire that callback when new data comes in? Should I try using the delegate methods instead? – Dylan Diamond Feb 08 '16 at 05:29
  • There is no much difference in using block based API or delegates, except that, this block based API fires the block when the whole data has been received. Yes, you will need to call the poll() after you have received the data. The code looks OK to me. – Shripada Feb 08 '16 at 05:40
  • This returns data in chunks, but I need to access it in realtime as the data comes in. – Dylan Diamond Feb 09 '16 at 23:21

0 Answers0