diff --git a/Networking.playground/Contents.swift b/Networking.playground/Contents.swift index 719027f..416b20b 100644 --- a/Networking.playground/Contents.swift +++ b/Networking.playground/Contents.swift @@ -5,59 +5,45 @@ //: It will serve up the current directory, so make sure to be in the directory containing episodes.json import UIKit -import XCPlayground +import PlaygroundSupport -typealias JSONDictionary = [String: AnyObject] +let url = URL(string: "http://localhost:8000/episodes.json")! -let url = NSURL(string: "http://localhost:8000/episodes.json")! - -struct Episode { +struct Episode: Decodable { let id: String let title: String } -extension Episode { - init?(dictionary: JSONDictionary) { - guard let id = dictionary["id"] as? String, - title = dictionary["title"] as? String else { return nil } - self.id = id - self.title = title - } -} +struct Media: Decodable {} -struct Media {} - -struct Resource { - let url: NSURL - let parse: NSData -> A? +struct Resource { + let url: URL + let parse: (Data) -> A? } + extension Resource { - init(url: NSURL, parseJSON: AnyObject -> A?) { + init(url: URL) { self.url = url self.parse = { data in - let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []) - return json.flatMap(parseJSON) + return try? JSONDecoder().decode(A.self, from: data) } } } extension Episode { - static let all = Resource<[Episode]>(url: url, parseJSON: { json in - guard let dictionaries = json as? [JSONDictionary] else { return nil } - return dictionaries.flatMap(Episode.init) - }) + static let all = Resource<[Episode]>(url: url) } final class Webservice { - func load(resource: Resource, completion: (A?) -> ()) { - NSURLSession.sharedSession().dataTaskWithURL(resource.url) { data, _, _ in + func load(resource: Resource, completion: @escaping (A?) -> ()) { + URLSession.shared.dataTask(with: resource.url) { data, _, _ in guard let data = data else { completion(nil) return @@ -68,8 +54,9 @@ final class Webservice { } -XCPlaygroundPage.currentPage.needsIndefiniteExecution = true +PlaygroundPage.current.needsIndefiniteExecution = true -Webservice().load(Episode.all) { result in - print(result) +Webservice().load(resource: Episode.all) { result in + print(result ?? "") } + diff --git a/README.md b/README.md index 1172001..f95360c 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,10 @@ # Swift Talk ## Networking -This is the code that accompanies Swift Talk Episode 1: [Networking](https://talk.objc.io/episodes/S01E01-networking) \ No newline at end of file +This is the code that accompanies Swift Talk Episode 1: [Networking](https://talk.objc.io/episodes/S01E01-networking) + +It has been slightly adapted to work with Xcode 9 / Swift 4. + +* some syntactical and type changes +* use of new JSONDecoder(), which simplifies code lot - see [Apple documentation](https://developer.apple.com/documentation/foundation/jsondecoder) +