我正在尝试使用iOS 8+中的Swift实现长轮询解决方案。
虽然该解决方案无疑有效,并且可以使主线程为空闲以进行UI交互,但内存使用不断增加,因此显然我做错了什么。我编写的类如下:
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()
}
}
}
}
我尝试使用Instruments对应用程序进行分析,但结果很令人困惑。希望有人可以指点我正确的方向。
谢谢