Jor*_*rke 5 long-polling grand-central-dispatch ios nsurlsession swift
我正在尝试使用 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()
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我曾尝试在 Instruments 中分析该应用程序,但结果令人困惑。我希望有人能指出我正确的方向。
谢谢
| 归档时间: |
|
| 查看次数: |
5026 次 |
| 最近记录: |