Last active
April 29, 2018 18:56
-
-
Save damodarnamala/d744c69051a4bd99d4ac94551a0957f7 to your computer and use it in GitHub Desktop.
Promise
This file contains 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 UIKit | |
import PromiseKit | |
let GET_POSTS = "https://jsonplaceholder.typicode.com/posts" | |
struct APIError : Error { | |
var message : String? | |
} | |
struct Post:Codable { | |
var userId : Int? | |
var id : Int? | |
var title : String? | |
var body : String? | |
} | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
let list: [Post] = self.asyncGetRequest().value?.then { data -> Void in return data } | |
print("\n Posts \(list.first )") | |
} | |
func asyncGetRequest<T: Decodable>() -> Promise<[T]> { | |
return Promise { resolve in | |
Alamofire.request(GET_POSTS).responseData().done { response in | |
guard let result = try? JSONDecoder().decode([T].self, from: response.data) else { | |
let error = APIError(message: "Error: Couldn't decode") | |
resolve.reject(error) | |
return | |
} | |
resolve.fulfill(result as [T]) | |
}.ensure { | |
}.catch { error in | |
resolve.reject(error) | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment