[英]iOS Swift - NSURLConnection.sendAsynchronousRequest cancel request
[英]ios Cancel NSURLConnection Swift
我有以下代碼:
func getStoryContent( cityID : String, completionHandler: (loaded: Bool, dataNil: Bool) -> ()) -> () {
let scriptUrl = "***"
var user_id = "nil"
if let userID = NSUserDefaults.standardUserDefaults().stringForKey("userId") {
user_id = userID
}
var params = ***
let myUrl = NSURL(string: scriptUrl);
let request: NSMutableURLRequest = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let data = params.dataUsingEncoding(NSUTF8StringEncoding)
request.timeoutInterval = 10
request.HTTPBody=data
request.HTTPShouldHandleCookies=false
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
do {
....code.....
當向用戶顯示圖像幻燈片時,它在后台運行,基本上可以下載更多要顯示的圖像並將它們附加到圖像數組中。 問題是用戶可以隨時退出幻燈片放映,在這種情況下,我需要取消此NSURLConnection
。 當用戶想要退出幻燈片放映時,我有一個執行的功能,但是我不確定要添加什么代碼以正確取消此連接。
NSURLConnection
的sendAsynchronousRequest
不可取消請求。 但是無論如何, NSURLConnection
已被棄用,您應該使用NSURLSession
。 並且NSURLSession
的dataTask
是可取消的。
因此,代替:
NSURLConnection.sendAsynchronousRequest(request, queue: queue) { response, data, error in
do {
....code.....
}
}
您可以使用:
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
do {
....code.....
}
}
task.resume()
而且,如果需要取消它,可以執行task.cancel()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.