Skip to content

Instantly share code, notes, and snippets.

@damodarnamala
Last active April 29, 2018 18:56
Show Gist options
  • Save damodarnamala/d744c69051a4bd99d4ac94551a0957f7 to your computer and use it in GitHub Desktop.
Save damodarnamala/d744c69051a4bd99d4ac94551a0957f7 to your computer and use it in GitHub Desktop.
Promise
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