-
-
Save shammelburg/979830cf0a4ee95c46bc5ce2bd599858 to your computer and use it in GitHub Desktop.
Generic way of loading data from the network.
This file contains hidden or 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
struct Resource<A> { | |
let pathComponent: String | |
let parse: AnyObject -> A? | |
} | |
extension Resource { | |
func loadAsynchronous(callback: A? -> ()) { | |
let session = NSURLSession.sharedSession() | |
let resourceURL = webserviceURL.URLByAppendingPathComponent(pathComponent) | |
session.dataTaskWithURL(resourceURL) { | |
data, response, error in | |
let json = data.flatMap { | |
try? NSJSONSerialization.JSONObjectWithData($0, options: NSJSONReadingOptions()) | |
} | |
callback(json.flatMap(self.parse)) | |
}.resume() | |
} | |
} | |
func jsonArray<A>(f: AnyObject -> A?) -> AnyObject -> [A]? { | |
return { | |
arr in | |
(arr as? [AnyObject]).map { $0.flatMap(f) } | |
} | |
} | |
let usersResource: Resource<[User]> = Resource(pathComponent: "/users", parse: jsonArray(User.init)) | |
let postsResource: Resource<[BlogPost]> = Resource(pathComponent: "/posts", parse: jsonArray(BlogPost.init)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment