I really like the Advanced NSOperations exapmle. But the more I immerse myself in this example the more I find unclear points. Now my question is about an incomprehensible behavior of NSURLSessionTaskState.
Let me explain what I encountered.
All code from Advanced NSOperations exapmle. I will show what changes I made and what they brought. So let's go.
We have the following code in DownloadEarthquakesOperation:
let task = NSURLSession.sharedSession().downloadTaskWithURL(url) { url, response, error in
self.downloadFinished(url, response: response as? NSHTTPURLResponse, error: error)
}Now change it to:
let task = NSURLSession.sharedSession().downloadTaskWithURL(url) { url, response, error in
print("Before the loop")
while 2 > 1 {
}
print("After the loop")
}And we have the following code in URLSessionTaskOperation:
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard context == &URLSessionTaksOperationKVOContext else { return }
if object === task && keyPath == "state" && task.state == .Completed {
task.removeObserver(self, forKeyPath: "state")
finish()
}
}Change it to:
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard context == &URLSessionTaksOperationKVOContext else { return }
if object === task && keyPath == "state" && task.state == .Completed {
print("Task state was changed to .Complete")
task.removeObserver(self, forKeyPath: "state")
finish()
}
}Now we can launch application and initialize the data download process. We'll see the text in console:
Before the loopLet's replace downloadTaskWithURL method to dataTaskWithURL. So the code in DownloadEarthquakesOperation:
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { url, response, error in
print("Before the loop")
while 2 > 1 {
}
print("After the loop")
}Again launch application. Now we have the text in console:
Before the loop
Task state was changed to .CompleteSo we can see that the task state changed to "Complete" before the code of completionHandler finished. But when we had downloadTaskWithURL where was not changing of the task state until the code of completionHandler finished (never in our case cause we have endless loop). So I would like to know why so different behavior. This is a bug or a feature?