Created
July 24, 2016 06:29
Star
You must be signed in to star a gist
objcio/S01E01-networking
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
//: To run this playground start a SimpleHTTPServer on the commandline like this: | |
//: | |
//: `python -m SimpleHTTPServer 8000` | |
//: | |
//: It will serve up the current directory, so make sure to be in the directory containing episodes.json | |
import UIKit | |
import PlaygroundSupport | |
typealias JSONDictionary = [String: AnyObject] | |
let url = NSURL(string: "http://localhost:8000/episodes.json")! | |
struct Episode { | |
let id: String | |
let title: String | |
} | |
extension Episode { | |
init?(dictionary: JSONDictionary) { | |
guard let id = dictionary["id"] as? String, | |
let title = dictionary["title"] as? String else { return nil } | |
self.id = id | |
self.title = title | |
} | |
} | |
struct Media {} | |
struct Resource<A> { | |
let url: NSURL | |
let parse: (NSData) -> A? | |
} | |
extension Resource { | |
init(url: NSURL, parseJSON: (AnyObject) -> A?) { | |
self.url = url | |
self.parse = { data in | |
let json = try? JSONSerialization.jsonObject(with: data as Data, options: []) | |
return json.flatMap(parseJSON) | |
} | |
} | |
} | |
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) | |
}) | |
} | |
final class Webservice { | |
func load<A>(resource: Resource<A>, completion: (A?) -> ()) { | |
URLSession.shared.dataTask(with: resource.url as URL) { data, _, _ in | |
guard let data = data else { | |
completion(nil) | |
return | |
} | |
completion(resource.parse(data)) | |
}.resume() | |
} | |
} | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
Webservice().load(resource: Episode.all) { result in | |
print(result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment