Last active
          March 30, 2017 21:31 
        
      - 
      
- 
        Save chelseatroy/c3f7196007e3e422426bf7d1b462e00c to your computer and use it in GitHub Desktop. 
    Asynchronous Calls with FutureKit
  
        
  
    
      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 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