How to Add Http Headers in Request Globally for iOS in Swift

iOS - not able to add http header of URLRequest


optional func webView(_ webView: WKWebView, 
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)

Use this delegate function. You can find headers of request in navigationAction.request.

How to add HTTP header to URL in Swift?

You can try

let url = URL(string: urlStr) 
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField:"Content-Type")
request.setValue("Bearer \(yourToken)", forHTTPHeaderField:"Authorization")
request.timeoutInterval = 60.0
URLSession.shared.dataTask(with: request) {
(data: Data?, response: URLResponse?, error: Error?) -> Void in
}.resume()

Or better use Alamofire

let headers : HTTPHeaders = ["Content-Type":"application/json",
"Authorization":"Bearer \(yourToken)"]
Alamofire.request(urlStr!, method: .post, parameters:[:], encoding: JSONEncoding.default, headers:headers).validate().responseJSON { response in
}

How to globally set custom headers in Swift app?

We have this documented right in the README.

var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
defaultHeaders["DNT"] = "1 (Do Not Track Enabled)"

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = defaultHeaders

let manager = Alamofire.Manager(configuration: configuration)

Then you need to use the new manager instead of the global Alamofire singleton.

manager.request(.GET, "https://httpbin.org/get")
.responseJSON { _, _, result in
debugPrint(result)
}

This will attach the DNT header to every request that is sent through this manager instance.

Each Manager instance has its own internal NSURLSession which also has its own configuration. Therefore, this override only works for this Manager instance. If you need these headers on a different Manager instance, you'll have to set it up the same way.

How to call REST full API by providing headers in Swift

By using Alamofire it's pretty simple.

let headers: HTTPHeaders = [
"Content-Type": "application/json",
"Session": "fb4e7f9b-0f31-4709-"
]

Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in
//Parse or print your response.
}

By using urlRequest

let header: HTTPHeaders = [
"Content-Type": "application/json",
"Session": "fb4e7f9b-0f31-4709-"
]
var urlRequest = URLRequest(url: URL(string: "your request url goes here."), cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
urlRequest.allHTTPHeaderFields = header
urlRequest.httpMethod = //.get, .post, .put
URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if let error = error {
print(error)
} else if let data = data ,let responseCode = response as? HTTPURLResponse {
do {
// Parse your response here.
}
}
catch let parseJSONError {
print("error on parsing request to JSON : \(parseJSONError)")
}
}
}.resume()

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

Adding custom http header field on all UIWebView requests

Based on David's comments, I used the following solution:

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let headerFields = request.allHTTPHeaderFields
var headerIsPresent = contains(request.allHTTPHeaderFields?.keys.array as [String], "X-Test-App")

if headerIsPresent || navigationType == UIWebViewNavigationType.Other {
return true
} else {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
dispatch_async(dispatch_get_main_queue(), {
let url = request.URL
var newRequest: NSMutableURLRequest = request as NSMutableURLRequest
// set new header
newRequest.addValue("MyValue", forHTTPHeaderField: "X-Test-App")

// reload the request
self.webView.loadRequest(newRequest)
})
})
return false
}
}

How to pass data into header while using URLSession in Swift?

Sample Image

ok approach you're answer with this solution

Sample Image



Related Topics



Leave a reply



Submit