Instantly share code, notes, and snippets.

anonymous /Bizarre.swift
Created Jul 17, 2016

Embed
What would you like to do?
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