Created
September 30, 2014 22:25
-
-
Save aqlla/06adbd3cfe8461d6f7ea to your computer and use it in GitHub Desktop.
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
import Foundation | |
typealias JSON = AnyObject | |
typealias JSONDict = Dictionary<String, JSON> | |
typealias JSONArray = Array<JSON> | |
struct User { | |
let id: Int | |
let name: String | |
let email: String | |
} | |
final class Box<A> { | |
let value: A | |
init(_ value: A) { | |
self.value = value | |
} | |
} | |
enum Result<A> { | |
case Error(NSError) | |
case Value(Box<A>) | |
} | |
func makeRequest() { | |
println("makeRequest called") | |
let url = NSURL(string: "http://104.131.48.79/api/user/test") | |
getUser(url) { result in | |
switch result { | |
case let .Value(boxedValue): | |
println(".Value") | |
let user = boxedValue.value | |
println("id: \(user.id) \nname: \(user.name) \nemail: \(user.email)") | |
case let .Error(error): | |
println(error) | |
} | |
} | |
} | |
func getUser(url: NSURL?, callback: (Result<User>) -> ()) { | |
let request = NSURLRequest(URL: url!) | |
let session = NSURLSession.sharedSession() | |
let queue = NSOperationQueue() | |
var responseHandler = {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in | |
println("getUser task started") | |
if error != nil { | |
callback(.Error(error)) | |
return | |
} | |
var jsonErrorOpt: NSError? | |
let jsonOptional: JSON! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonErrorOpt) | |
if jsonErrorOpt != nil { | |
callback(Result.Error(jsonErrorOpt!)) | |
return | |
} | |
if let json = jsonOptional as? JSONDict { | |
if let id = json["id"] as AnyObject? as? Int { | |
if let name = json["name"] as AnyObject? as? String { | |
if let email = json["email"] as AnyObject? as? String { | |
let user = User(id: id, name: name, email: email) | |
callback(.Value(Box(user))) | |
return | |
} | |
} | |
} | |
} | |
// if we couldn't parse all the properties then send back an error | |
callback(.Error(NSError())) | |
} | |
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler: responseHandler) | |
println("getUser task called") | |
} | |
makeRequest() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment