HTTP Long Polling in Swift

旧城冷巷雨未停 提交于 2019-12-21 02:41:32

问题


I am trying to implement a long-polling solution in Swift using iOS 8+.

While the solution undoubtedly works and leaves the main thread free for UI interactions, the memory usage climbs continuously so I am obviously doing something wrong. The class I have written is as follows:

enum LongPollError:ErrorType{
    case IncorrectlyFormattedUrl
    case HttpError
}

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

    var longPollDelegate: LongPollingDelegate
    var request: NSURLRequest?

    init(delegate:LongPollingDelegate){
        longPollDelegate = delegate
    }

    public func poll(endpointUrl:String) throws -> Void{
        let url = NSURL(string: endpointUrl)
        if(url == nil){
            throw LongPollError.IncorrectlyFormattedUrl
        }
        request = NSURLRequest(URL: url!)
        poll()
    }

    private func poll(){
        dispatch_async(GlobalBackgroundQueue) {
            self.longPoll()
        }
    }

    private func longPoll() -> Void{
        autoreleasepool{
            do{
                let urlSession = NSURLSession.sharedSession()
                let dataTask = urlSession.dataTaskWithRequest(self.request!, completionHandler: {
                    (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
                    if( error == nil ) {
                        self.longPollDelegate.dataReceived(data)
                        self.poll()
                    } else {
                        self.longPollDelegate.errorReceived()
                    }
                })
                dataTask.resume()
            }
        }
    }
}

I have tried profiling the app in Instruments but the results are confusing. I am hoping somebody can point me in the right direction.

Thanks


回答1:


LongPollDelegate is strong so you have a retain cycle. Make it a weak variable.



来源:https://stackoverflow.com/questions/34513887/http-long-polling-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!