Created
October 4, 2016 16:15
-
-
Save colourful987/d761566a834862aaaec00830104ffe89 to your computer and use it in GitHub Desktop.
Swift Talk Episode 1 - 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
import Foundation | |
let url = URL(string:"http://localhost/test1.json")! | |
typealias JSONDictionary = [String:AnyObject] | |
// 资源的链接 & 解析闭包 | |
struct Resource<A>{ | |
let url: URL | |
let parse : (Data) -> A? | |
} | |
// 返回数据的结构体 | |
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 | |
} | |
} | |
// 服务器 相当于你有资源 让别人来帮你加载 解析还是你来 | |
final class WebService { | |
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 | |
} | |
completion(resource.parse(data)) | |
}.resume() | |
} | |
} | |
extension Sequence { | |
public func failingFlatMap<T>( transform: (Self.Iterator.Element) throws -> T?) rethrows -> [T]? { | |
var result: [T] = [] | |
for element in self { | |
guard let transformed = try transform(element) else { return nil }// 一旦有错误 直接跳出 | |
result.append(transformed) | |
} | |
return result | |
} | |
} | |
extension Resource { | |
init(url:URL,parseJSON:@escaping (AnyObject) -> A?) { | |
self.url = url | |
self.parse = { data in | |
let json = try? JSONSerialization.jsonObject(with: data, options: []) | |
return (json as AnyObject?).flatMap(parseJSON) | |
} | |
} | |
} | |
let episodesResource = Resource<[Episode]>(url:url,parseJSON:{ | |
json in | |
guard let dictionaries = json as? [JSONDictionary] else {return nil} | |
return dictionaries.flatMap(Episode.init) | |
}) | |
var results :[Episode]? = [] | |
WebService().load(resource: episodesResource) { (result) in | |
results = result | |
//print(result) | |
} | |
Thread.sleep(forTimeInterval: 10) // 为了足够的时间获取到结果 再退出 | |
print(results) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment