Folks, Trying to figure out the right programmatic approach to returning data from external API calls.
Before I start and create my own quick code reuse framework (which manages all the rest api calls for my application), I would like to ask the community how they handle the following situation:
Here we have a button that is used to enter the system, we need to call our authorization service and respond to what we return.
ViewController:
import myLib
@IBAction func loginButtonTapped(sender: AnyObject) {
let email = emailField.text!
let password = pwField.text!
let loginResult = myLib.login(email,password)
if (loginResult.success) {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isUserLoggedIn")
NSUserDefaults.standardUserDefaults().synchronize()
self.dismissViewControllerAnimated(true, completion: nil)
} else {
displayAlertMessage(loginResult.message)
}
}
myLib.login:
import Foundation
import Alamofire
import SwiftyJSON
public func Login(email: String, password: String, completion: ((success: Bool, message: String?, token: String?) -> Void)) {
let parameters: [String: String] = [
"username" : email,
"password" : password
]
let endpoint = "https://api.foo.bar/login"
Alamofire.request(.POST, endpoint, parameters: parameters, encoding: .JSON)
.responseJSON { response in
guard response.result.error == nil else {
print(response.result.error!)
completion(success: false, message: "error calling POST on /account/login", token: nil)
return
}
if let value = response.result.value {
let apiResponseJSONBody = JSON(value)
completion(success: true, message: nil, token: apiResponseJSONBody["token"].string)
}
}
}
- Is it right to pass results back as structures? I noticed that we must make the structure open in order to bring it back.
Thank! I appreciate all the feedback.
update: : Swift Alamofire + Promise