alamofire api call in swift 5 code example
Example: use alamofire to login in swift 5
protocol AccessTokenStorage: class {
typealias JWT = String
var accessToken: JWT { get set }
}
final class RequestInterceptor: Alamofire.RequestInterceptor {
private let storage: AccessTokenStorage
init(storage: AccessTokenStorage) {
self.storage = storage
}
func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
guard urlRequest.url?.absoluteString.hasPrefix("https://api.authenticated.com") == true else {
return completion(.success(urlRequest))
}
var urlRequest = urlRequest
urlRequest.setValue("Bearer " + storage.accessToken, forHTTPHeaderField: "Authorization")
completion(.success(urlRequest))
}
}