Skip to content

Instantly share code, notes, and snippets.

@Savchukv
Created May 31, 2017 14:12
Show Gist options
  • Save Savchukv/2f889558cb18ec34c73bbfd424342a35 to your computer and use it in GitHub Desktop.
Save Savchukv/2f889558cb18ec34c73bbfd424342a35 to your computer and use it in GitHub Desktop.
Example Alamofire request for login with constants string
//
// 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