快速长轮询

时间:2016-02-08 04:32:05

标签: ios swift nsurlsession

我正在尝试连接到一个url然后从它接收更新,因为它在一个名为HTTP Long Polling的方法中不断返回新数据。我找到了这个例子HTTP Long Polling in Swift,但它根本不起作用。数据返回一次,但不会连续返回,它在CURL中工作。这是我的代码:

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()
            }
        }
    }

0 个答案:

没有答案