How to Use Alamofire with Custom Headers

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
}

}

How to use Alamofire with custom headers for POST request

Here's an example of how I use it with custom headers:

    var manager = Manager.sharedInstance
// Specifying the Headers we need
manager.session.configuration.HTTPAdditionalHeaders = [
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/vnd.lichess.v1+json",
"X-Requested-With": "XMLHttpRequest",
"User-Agent": "iMchess"
]

Now whenever you make a request, it'll use the specified headers.

Your code refactored:
remember to import Alamofire

    let aManager = Manager.sharedInstance
manager.session.configuration.HTTPAdditionalHeaders = [
"Authorization": "Bearer \(accessToken)" ]

let URL = url + "/server/rest/action"

request(.POST, URL, encoding: .JSON)
.responseJSON {
(request, response, data, error) -> Void in

println("REQUEST: \(request)")
println("RESPONSE: \(response)")
println("DATA: \(data)")
println("ERROR: \(error)")
}

This is request signature request(method: Method, URLString: URLStringConvertible>, parameters: [String : AnyObject]?, encoding: ParameterEncoding)

As you can see you don't have to pass an NSURL in it, just the string of the URL, Alamofire takes care of the rest.

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

Alamofire custom header not working

You have to pass Alamofire a NSMutableURLRequest with your customized header. Check out this issue for a better explanation.

        var request = NSMutableURLRequest(URL: NSURL(string: "YOUR URL HERE")!)
request.HTTPMethod = "GET"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
request.addValue("application/vnd.dribbble.v1.text+json", forHTTPHeaderField: "Accept")
//Add paramaters (Optional)
let param = ["foo": "bar"]
let encoding = Alamofire.ParameterEncoding.URL
(request, _) = encoding.encode(request, parameters: param)
Alamofire.request(request).responseJSON { response in
//DO SOMETHING WITH YOUR RESPONSE OBJECT
}

Hope this helps :)

How to send request in Alamofire with parameters and headers using POST method in swift

Alamofire 4.0

let headers = ["Content-Type":"Application/json"]


Alamofire.request(requestString, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
print("Request \(response.request)")

print("RESPONSE \(response.result.value)")
print("RESPONSE \(response.result)")
print("RESPONSE \(response)")


switch response.result {
case .success:


case .failure(let error):


}
}

in 3.0 u can also add headers like this . In parameters to func

Upload Photo / File with JSON and custom headers via Swift 3 and Alamofire 4 | iOS | Swift

Try This Code for Multiple upload Images in Single Request, This code is already working.

     // For Pass Valid Parameters & number of Images in Array in Image Upload Function
var dicImgData : NSMutableDictionary? = NSMutableDictionary()

if let img = UIImage(named: "Your Image") {
if let data:Data = UIImagePNGRepresentation(img) {
var imageData : NSData = data
dicImgData! .setObject(imageData, forKey: "data" as NSCopying)
dicImgData! .setObject("file", forKey: "name" as NSCopying)
dicImgData! .setObject("file.png", forKey: "fileName" as NSCopying)
dicImgData! .setObject("image/png", forKey: "type" as NSCopying)

let dicParameter = [
"hometown": "yalikavak",
"living": "istanbul"
]

self.uploadImage(url: "Your URL", Parameter: dicParameter, Images: [dicImgData])
}
}

Upload Function

    func uploadImage (url: String, Parameter param : NSDictionary, Images arrImage: NSArray) -> Void
{
var requestURL : String! = url
let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json",
]

print("---------------------")
print("Request URL :- \(requestURL)")
print("---------------------")

Alamofire.upload(multipartFormData: { (data) in

for (key, value) in param {
data.append((value as! String).data(using: .utf8)!, withName: key as! String)
}

for imageInfo in arrImage
{
var dicInfo : NSDictionary! = imageInfo as! NSDictionary
data.append(dicInfo["data"] as! Data, withName: dicInfo["name"] as! String, fileName: dicInfo["fileName"] as! String, mimeType: dicInfo["type"] as! String)
dicInfo = nil
}

}, to: requestURL, method: .post , headers:nil, encodingCompletion: { (encodeResult) in
switch encodeResult {
case .success(let upload, _, _):

upload.responseJSON(completionHandler: { (response) in

switch response.result
{
case .success(let responseJSON):
guard let dicResponse = responseJSON as? NSDictionary else{
return
}

print("Response : \((dicResponse))")

case .failure(let error):

print(error)

break
}
})
case .failure(let error):
print(error)
break
}
})
}


Related Topics



Leave a reply



Submit