Swift中的HTTP长轮询 [英] HTTP Long Polling in Swift

查看:340
本文介绍了Swift中的HTTP长轮询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用iOS 8+在Swift中实现长轮询解决方案。

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

虽然解决方案无疑可行,并且主线程可以自由进行UI交互,但内存使用量不断攀升,所以我显然做错了什么。我写的课程如下:

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.

谢谢

推荐答案

LongPollDelegate强大,因此您有一个保留周期。把它变成一个弱变量。

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

这篇关于Swift中的HTTP长轮询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆