3

This is my header

Screen Shot

I had already add those params to url, how to add the header with value "bearer" and api_key to url in swift

 var urlComponents = URLComponents(string: "https://api.yelp.com/v3/businesses/search")!

    urlComponents.queryItems = [
        URLQueryItem(name: "query", value: "landmarks"),
        URLQueryItem(name: "ll", value: "\(latitude), \(longitude)"),
    ]

3 Answers 3

9

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 
}
Sign up to request clarification or add additional context in comments.

Comments

6
let urlString = ""
let parameters = ["categories.confident": "true", "source.name" : "The New York Times", "cluster" : "false", "cluster.algorithm" : "lingo", "sort_by" : "published_at", "sort_direction" : "desc", "cursor" : "*", "per_page" : "10"]
let headers = ["X-AYLIEN-NewsAPI-Application-ID": "App-ID-Here", "X-AYLIEN-NewsAPI-Application-Key": "App-Key-Here"]

var urlComponents = URLComponents(string: urlString)

var queryItems = [URLQueryItem]()
for (key, value) in parameters {
    queryItems.append(URLQueryItem(name: key, value: value))
}

urlComponents?.queryItems = queryItems

var request = URLRequest(url: (urlComponents?.url)!)
request.httpMethod = "GET"

for (key, value) in headers {
    request.setValue(value, forHTTPHeaderField: key)
}

let task = URLSession.shared.dataTask(with: request) { (data, response, error) -> Void in
    print(response)
}
task.resume()

Comments

0

It worked for me.Try this once.

 func handleData() {

        let urlStr = "YOUR URL"
        let param = ["email":"[email protected]","password":"abc@1234","X-API-KEY":"YOURAPIKEY"]

        let user = "admin"
        let password = "1234"
        let credentialData = "\(user):\(password)".data(using: String.Encoding.utf8)!
        let base64Credentials = credentialData.base64EncodedString(options: [])
        let headers = ["Authorization": "Basic \(base64Credentials)"]

        Alamofire.request(urlStr, method: .post, parameters: param, encoding: JSONEncoding.default, headers:headers).responseJSON{
            response in

            switch response.result{
            case .success:
                print(response)
                break

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.