Swift Alamofire Add Custom Header to All Requests

how to use Alamofire with custom headers

According to the official documentation, modifying the session configuration is not recommended:

This is not recommended for Authorization or Content-Type headers.
Instead, use URLRequestConvertible and ParameterEncoding,
respectively.

So an example usage of URLRequestConvertible for authorization would be:

enum Router: URLRequestConvertible {
static let baseUrlString = "some url string"

case Get(query: String)

var URLRequest: NSMutableURLRequest {
let (path: String, parameters: [String: AnyObject]?) = {
switch self {
case .Get(let query):
return ("/get", ["q": query])
}
}()

let URL = NSURL(string: Router.baseUrlString)!
let URLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
// set header fields
URLRequest.setValue("a", forHTTPHeaderField: "Authorization")

let encoding = Alamofire.ParameterEncoding.URL
return encoding.encode(URLRequest, parameters: parameters).0
}
}

and when you want to make a request:

Manager.sharedInstance.request(Router.Get(query: "test"))

More info about URLRequestConvertible: https://github.com/Alamofire/Alamofire#urlrequestconvertible

Old Answer

As of Alamofire v1.0 Pers answer no longer works. In the new version additional headers should be added to the HTTPAdditionalHeaders property of NSURLSessionConfiguration

Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization": authorizationToken]

More info here: https://github.com/Alamofire/Alamofire/issues/111

Alamofire POST request with headers

Add Headers in this way

    let headers = ["Authorization" : "Bearer "+accessToken!+"",
"Content-Type": "application/json"]

Alamofire.request(URL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON
{ (response:DataResponse) in
switch(response.result)
{
case .success(let value):
//for Json serialization add in success:

let JSON = try JSONSerialization.jsonObject(with: response.data! as Data, options:JSONSerialization.ReadingOptions(rawValue: 0))

guard let JSONDictionary: NSDictionary = JSON as? NSDictionary else {

return
}
completionHandler(JSONDictionary as? NSDictionary, nil)
case .failure(let error):
completionHandler(nil, error as NSError?)
break
}

}

Alamofire Request call with: Parameters, Headers and Body not working

Question One

You need to encode as a querystring

let urlString   = "https://intelipos.dynalias.net/ioc/rest.asp"
let parameters = ["action":"heartbeat"]
let headers: HTTPHeaders = ["Content-Type":"application/json"]

AF.request(urlString, method: .post, parameters: parameters, encoding: URLEncoding.queryString, headers: headers).responseJSON { response in
switch response.result {
case .success:
print("Validation Successful")
case let .failure(error):
print(error)
}
}

Question Two

You have to prepare an encodable model and pass it in parameters argument and set encoding to JSONEncoding.default

Refer this article: https://medium.com/whoknows-swift/swift-4-decodable-encodable-3085305a9618

Swift Alamofire 4 add header to request without custom request adapter

The method signature changed. This should work for you:

Alamofire.request(url, method: .post , parameters: parameters, encoding: JSONEncoding.default, headers: headers)
.responseJSON { response in
if response.result.isSuccess {
let time = DispatchTime(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds) + Double(1 * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time) {
self.loadAreasFromServer();
self.busy = false;
}
}
}

how to set a default http header with alamofire

Your code never make use of your custom manager, use following code:

class CustomManager: Manager {
static public let manager = CustomManager.generateManager()
class func generateManager()-> CustomManager {
var defaultHeaders = Alamofire.Manager.defaultHTTPHeaders ?? [:]
defaultHeaders["x-token""] = "token"
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = defaultHeaders
let manager = CustomManager(configuration: configuration)
return manager
}
}

class UserService : NSObject {

class func addFriend(user:LoggedUser, uname:String, callback:((success: Bool, errorMsg: String?)->Void)) {

let params:[String : AnyObject] = ["uname": uname]

let url = AppConfig.sharedInstance().baseURL() + "/user/\(user.userId!)/friends"
CustomManager.manager(.POST, url , parameters:params, encoding:.JSON)
.responseJSON(options: .MutableContainers, completionHandler:{ (request, response, JSON, error) -> Void in

// ...
}
}

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.



Related Topics



Leave a reply



Submit