Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 10 additions & 11 deletions Networking.playground/Contents.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@
//: 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 = NSURL(string: "http://localhost:8000/episodes.json")!
let url = URL(string: "http://localhost:8000/episodes.json")!


struct Episode {
Expand All @@ -21,7 +20,7 @@ struct Episode {
extension Episode {
init?(dictionary: JSONDictionary) {
guard let id = dictionary["id"] as? String,
title = dictionary["title"] as? String else { return nil }
let title = dictionary["title"] as? String else { return nil }
self.id = id
self.title = title
}
Expand All @@ -32,15 +31,15 @@ struct Media {}


struct Resource<A> {
let url: NSURL
let parse: NSData -> A?
let url: URL
let parse: (Data) -> A?
}

extension Resource {
init(url: NSURL, parseJSON: AnyObject -> A?) {
init(url: URL, parseJSON: @escaping (Any) -> A?) {
self.url = url
self.parse = { data in
let json = try? NSJSONSerialization.JSONObjectWithData(data, options: [])
let json = try? JSONSerialization.jsonObject(with: data, options: [])
return json.flatMap(parseJSON)
}
}
Expand All @@ -56,8 +55,8 @@ extension Episode {


final class Webservice {
func load<A>(resource: Resource<A>, completion: (A?) -> ()) {
NSURLSession.sharedSession().dataTaskWithURL(resource.url) { data, _, _ in
func load<A>(_ resource: Resource<A>, completion: @escaping (A?) -> ()) {
URLSession.shared.dataTask(with: resource.url) { data, _, _ in
guard let data = data else {
completion(nil)
return
Expand All @@ -68,7 +67,7 @@ final class Webservice {
}


XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
PlaygroundPage.current.needsIndefiniteExecution = true

Webservice().load(Episode.all) { result in
print(result)
Expand Down