Created
July 17, 2016 17:11
-
-
Save anonymous/5558ac9a27a10e6a2efd277f173e9fbb to your computer and use it in GitHub Desktop.
Inconsistency between NSURLSessionDataTask and NSURLSessionDownloadTask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// RaceCondition | |
// | |
// Created by Oliver Foggin on 17/07/2016. | |
// Copyright © 2016 Oliver Foggin. All rights reserved. | |
// | |
import Foundation | |
import XCPlayground | |
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true | |
class FooBar: NSObject { | |
func startDownload() { | |
let url = NSURL(string: "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_month.geojson")! | |
// let task = NSURLSession.sharedSession().dataTaskWithURL(url) { | |
// (data, response, error) in | |
// print("completion handler started") | |
// self.downloadFinishe() | |
// } | |
let task = NSURLSession.sharedSession().downloadTaskWithURL(url) { | |
url, response, error in | |
print("completion handler started") | |
self.downloadFinishe() | |
} | |
task.addObserver(self, forKeyPath: "state", options: [], context: nil) | |
task.resume() | |
print("download started") | |
} | |
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { | |
if let task = object as? NSURLSessionTask where keyPath == "state" && task.state == .Completed { | |
task.removeObserver(self, forKeyPath: "state") | |
print("Task completed") | |
} | |
} | |
func downloadFinishe() { | |
print("download finished") | |
var numbers = [Int]() | |
for _ in 0...1000 { | |
numbers.append(Int(arc4random_uniform(10))) | |
} | |
numbers = numbers.sort() | |
print(numbers[500]) | |
print("completion processing finished") | |
} | |
} | |
let foobar = FooBar() | |
foobar.startDownload() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment