How can I use Alamofire to add auth header to each request, and do something if the response is 401?
As per to your requirement, I would personally prefer to have a intermediate class for calling methods of Alamofire.
For that you can add auth header on each web service call.
Here is the following example for Intermediate class.
WebClient.swift
class WebClient: SessionManager {
static let sharedManager = WebClient()
func responseRequest(_ url: String, method: Alamofire.HTTPMethod, parameter: Parameters? = nil, encoding: ParameterEncoding, header: HTTPHeaders? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Void {
self.request(url, method: method, parameters: parameter, encoding: encoding, headers: header).response { response in
completionHandler(response)
}
} }
You can modify above class as per requirement or you can directly pass header in request method for each webservice call.
Authorization Header not setting in Alamofire 5?
After setting the Authorization header in your URLRequest
:
urlRequest.addValue("\(APIConstants.API.token.rawValue) \(token.key)", forHTTPHeaderField: "Authorization")
then you override all the request's headers by setting headers
property:
urlRequest.headers = headers
A nice solution would be to update the headers
that you already created above, like this:
var headers: HTTPHeaders = [
.contentType(APIConstants.ContentType.json.rawValue),
.accept(APIConstants.ContentType.json.rawValue),
]
if let token = token {
headers.add(.authorization("\(APIConstants.API.token.rawValue) \(token.key)"))
}
urlRequest.headers = headers
Basic auth header in Alamofire
let user = "your username"
let password = "your password"
let credentialData = "\(user):\(password)".data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
let base64Credentials = credentialData.base64EncodedString()
let headers = [
"Authorization": "Basic \(base64Credentials)",
"Accept": "application/json",
"Content-Type": "application/json" ]
//put slash before \ (base64Credentials)
Alamofire.request("place your url", method: .get, parameters: nil,encoding: URLEncoding.default, headers: headers) .responseJSON { response in
switch response.result {
case .success(_):
//your success code
}
case .failure(_):
//your failure code
}
}
How to add authorization on header using Swift 3.0 + Alamofire 4.0
Use Authorization
as your header key.
However, you shouldn't need to do it, considering HTTP header keys are case-insensitive, the issue is probably on the server.
Related Topics
How to Get All the Sundays in Array of Date iOS
Xcode 6 & Swift: Black Bars Appear Above and Below the Viewcontroller on iOS 7 iPhone 5 Device
Swift Continuous Rotation Animation Not So Continuous
iOS 10 Issue: Uiscrollview Not Scrolling, Even When Contentsize Is Set
Start/Stop Image View Rotation Animations
How Parsing Firebase Fdatasnapshot JSON Data in Swift
How to Fill a Circle Color by Percentage Value
Transforming a Cashapelayer to a Specific Size in Swift
Convenience Initialization of Uinavigationcontroller Subclass Makes Subclass Constant Init Twice
My Uiviews Muck-Up When I Combine Uipangesturerecognizer and Autolayout
iOS How to Correctly Handle Orientation When Capturing Video Using Avassetwriter
How to Schedule a Same Local Notification in Swift
Swift Spritekit Playing Audio in the Background
iOS + Swift, How to Redirect to Itunes Purchase Page
Get All Urls for Resources in Sub-Directory in Swift
How to Simultaneously Satisfy Constraints with Keyboard and Uitoolbar