Created
May 31, 2017 14:12
-
-
Save Savchukv/2f889558cb18ec34c73bbfd424342a35 to your computer and use it in GitHub Desktop.
Example Alamofire request for login with constants string
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
// | |
// BackendService.swift | |
// | |
// Created by Vasiliy Savchuk on 27.01.17. | |
// Copyright © 2017 All rights reserved. | |
// | |
enum API { | |
static var token: String? | |
static var tokenType: String? | |
static let headers: HTTPHeaders = [ | |
"Authorization": "\(API.tokenType ?? "") \(API.token ?? "")" | |
] | |
} | |
static func loginUser(email: String, password: String, handler:@escaping (JSON?, NSError?) -> Void) { | |
let urlUserParameters: [String: String] = [Constant.JSON.Email: email, | |
Constant.JSON.Password: password, | |
Constant.JSON.ClientId : Constant.API.ClientId, | |
Constant.JSON.ClientSecret : Constant.API.ClientSecret] | |
Alamofire.request("http://your.com", method: .post, parameters: urlUserParameters, encoding: URLEncoding.default, headers: nil).validate().responseJSON { response in | |
if 422 == response.response?.statusCode { | |
let error = NSError.init(domain: "", code: 422, userInfo: [ NSLocalizedDescriptionKey : NSLocalizedString("Please create account", comment: "") ]) | |
handler(nil, error) | |
} else if let JSONRequest = response.result.value { | |
let json = JSON(JSONRequest) | |
let token = json["access_token"].stringValue | |
let tokenType = json["token_type"].stringValue | |
API.token = token | |
API.tokenType = tokenType | |
handler(json, nil) | |
} else { | |
handler(nil, response.result.error as NSError?) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment