Skip to content

Instantly share code, notes, and snippets.

@pablocarrillo
Last active August 29, 2015 14:22
Show Gist options
  • Save pablocarrillo/127998653563223b91f7 to your computer and use it in GitHub Desktop.
Save pablocarrillo/127998653563223b91f7 to your computer and use it in GitHub Desktop.
PromiseKit 2 Example with Promise<T>
//
// ViewController2.swift
//
// Created by Pablo Carrillo on 09/06/2015.
// Copyright (c) 2015 Calvium. All rights reserved.
//
import UIKit
import Alamofire
import PromiseKit
class ViewController2: UIViewController {
var properties = ApplicationProperties()
var server: SomeAPIConfig!
var manager: Alamofire.Manager?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
server = SomeAPIConfig(clientId: properties.someAPIClientId, url: properties.someAPIBaseUrl)
var sessionManager = SessionManager(config: server)
sessionManager.login("user", password: "pasword") { (status) -> Void in
var result = ""
switch status{
case .Valid:
result = "valid"
default:
result = "Something went wrong"
}
println("Session with status \(result)")
sessionManager.token({ (status, token) -> Void in
println("The token is \(token)")
firstly{
self.connectToServer(token!)
}.then { Void -> Void in
println("The promise was executed")
}.recover { error -> Promise<Void> in
println("Error \(error)")
return Promise()
}.finally { _ -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}
})
}
}
func connectToServer(token: String, completion:(Void)->Void)-> Void{
var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
defaultHeaders["Authorization"] = "Bearer \(token)"
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = defaultHeaders
self.manager = Alamofire.Manager(configuration: configuration)
let path = "https://path/to/server/api"
self.manager!.request(.GET, server.url + path, parameters: nil)
.responseString { (request, response, data, error) in
println(request)
println(response)
println(error)
println(data)
completion()
}.responseJSON() { (request, response, json, error) -> Void in
println(json)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func connectToServer(token: String) ->(Promise<Void>){
return Promise{ fulfill, reject in
self.connectToServer(token, completion:{
println("Running the promise Block")
fulfill()
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment