Skip to content

Instantly share code, notes, and snippets.

Created July 17, 2016 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/5558ac9a27a10e6a2efd277f173e9fbb to your computer and use it in GitHub Desktop.
Save anonymous/5558ac9a27a10e6a2efd277f173e9fbb to your computer and use it in GitHub Desktop.
Inconsistency between NSURLSessionDataTask and NSURLSessionDownloadTask
//
// 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