Skip to content

Instantly share code, notes, and snippets.

View aalemi97's full-sized avatar

AliReza Alemi aalemi97

View GitHub Profile
func refreshToken(completion: @escaping (_ isSuccess: Bool) -> Void) {
guard let apiKey = UserDefaultsManager.shared.getUserCredentials().apiKey,
let secretKey = UserDefaultsManager.shared.getUserCredentials().secretKey else { return }
let parameters = ["grant_type": "client_credentials", "client_id": apiKey, "client_secret": secretKey]
AF.request(authorize, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
if let data = response.data, let token = (try? JSONSerialization.jsonObject(with: data, options: [])
as? [String: Any])?["access_token"] as? String {
UserDefaultsManager.shared.setToken(token: token)
print("\nRefresh token completed successfully. New token is: \(token)\n")
completion(true)
func retry(_ request: Request, for session: Session, dueTo error: Error,
completion: @escaping (RetryResult) -> Void) {
guard request.retryCount < retryLimit else {
completion(.doNotRetry)
return
}
print("\nretried; retry count: \(request.retryCount)\n")
refreshToken { isSuccess in
isSuccess ? completion(.retry) : completion(.doNotRetry)
}
func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
var request = urlRequest
guard let token = UserDefaultsManager.shared.getToken() else {
completion(.success(urlRequest))
return
}
let bearerToken = "Bearer \(token)"
request.setValue(bearerToken, forHTTPHeaderField: "Authorization")
print("\nadapted; token added to the header field is: \(bearerToken)\n")
completion(.success(request))
func request(_ url: String, method: HTTPMethod = .get, parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.queryString, headers: HTTPHeaders? = nil,
interceptor: RequestInterceptor? = nil, completion: @escaping completionHandler) {
AF.request(url, method: method, parameters: parameters, encoding: encoding,
headers: headers, interceptor: interceptor ?? self).validate().responseJSON { (response) in
if let data = response.data {
completion(.success(data))
} else {
completion(.failure(.unavailableServer))
}
import Foundation
class UserDefaultsManager {
enum Key: String {
case apiKey
case secretKey
case token
case isSignedIn
}
static let shared: UserDefaultsManager = {
return UserDefaultsManager()
import Alamofire
class NetworkManager {
static let shared: NetworkManager = {
return NetworkManager()
}()
typealias completionHandler = ((Result<Data, CustomError>) -> Void)
var request: Alamofire.Request?
let retryLimit = 3
let authorize = "https://api.petfinder.com/v2/oauth2/token"
func authorize(parameters: [String: Any]?, completion: @escaping completionHandler) {
func login(apiKey: String, secretKey: String) {
let parameters = ["grant_type": "client_credentials", "client_id": apiKey, "client_secret": secretKey]
NetworkManager.shared.authorize(parameters: parameters) { (result) in
switch result {
case .success(let data):
if let token = (try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any])?["access_token"] as? String {
UserDefaultsManager.shared.signIn(apiKey: apiKey, secretKey: secretKey, token: token)
}
case .failure(let error):
print(error)