Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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