我有一段程式碼如下:
class func getURL(urlString:String, httpMethod:String, completion:(NSDictionary) -> Void) {
let request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: urlString)
request.HTTPMethod = httpMethod
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request,completionHandler: {(data:NSData?, response: NSURLResponse?, error:NSError?) -> Void in
do{
if let _ = NSString(data:data!, encoding: NSUTF8StringEncoding) {
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
Log.msg("load completed \(urlString)")
completion(jsonDictionary)
}
} catch {
Log.msg("bad things happened")
completion(NSDictionary())
}
}).resume()
}
NSURLSession 似乎都是同一條執行緒在執行,因為當我多次呼叫此方法時,都會要等前面
的Request做完,下一次Request才會執行。
我想問的是,是否可在前一次的Request未完成時,只要再次呼叫就立刻中斷前一次的作業呢?