Skip to content

Instantly share code, notes, and snippets.

@chelseatroy
Last active March 30, 2017 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chelseatroy/c3f7196007e3e422426bf7d1b462e00c to your computer and use it in GitHub Desktop.
Save chelseatroy/c3f7196007e3e422426bf7d1b462e00c to your computer and use it in GitHub Desktop.
Asynchronous Calls with FutureKit
import FutureKit
import SwiftyJSON
class VillainService {
let url: String
var session: URLSession = URLSession.shared
func getVillainList() -> Future<VillainResponse> {
let promise = Promise<VillainResponse>()
var request = URLRequest(url: URL(string: "http://www.wearevillains.com/team"))
request.httpMethod = "GET"
let task = session.dataTask(with: request) { data, response, error in
if error != nil {
promise.completeWithFail(error!)
} else {
do {
if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
let dataAsJson = JSON(convertedJsonIntoDict)
promise.completeWithSuccess(APIRootResourceLinks.init(fromJSON: dataAsJson)!)
}
} catch let error as NSError {
promise.completeWithFail(error)
}
}
task.resume()
return promise.future
}
}
extension Villain : JSONDeserializable {
init?(fromJSON json: JSON) {
guard let name = json["name"].string else { return nil }
guard let specialty = json["specialty"].string else { return nil }
}
}
extension VillainResponse : JSONDeserializable {
init?(fromJSON json: JSON) {
guard let
villainCount = json["villainCount"].int,
let villains = json["villains"].array {
for (index, vill) in villains.enumerated() {
if let villain = Villain(fromJson: json["villains"][index]) {
villains.append(villain)
}
}
} else { return nil }
count = villainCount
villains = villains
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment