Home > database >  I need help implementing Bearer Token in my API code but I don't know how :(
I need help implementing Bearer Token in my API code but I don't know how :(

Time:11-18

I wrote the code for my API but I didn't wrote the code for the Bearer Token since I don't know how to do it properly since I am new to swift :) so if anyone could help me or reference me to a link on how to do it :)

This Is all I have about it in my code but its not working :(

                let headers = [
                "content-type": "application/json",
                "authorizetoken": "NjQzODM2N0NDNDM4NDhCNDk3RkU0NjA0QUY0NjVENkE=",
                "cache-control": "no-cache",
                ]
    
    }
    
    var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 120)
            request.httpMethod = "GET"
            request.allHTTPHeaderFields = headers

CodePudding user response:

You need to update your allHTTPHeaderFields

request.allHTTPHeaderFields = [
            "content-type": "application/json",
            "authorizetoken": "Bearer NjQzODM2N0NDNDM4NDhCNDk3RkU0NjA0QUY0NjVENkE=",
            "cache-control": "no-cache",
            ]

CodePudding user response:

import Foundation
func ApiCall(urlString:String) {
   let url = URL(string: urlString)!

   var request = URLRequest(url: url)
   request.allHTTPHeaderFields = [
            "content-type": "application/json",
            "authorizetoken": "NjQzODM2N0NDNDM4NDhCNDk3RkU0NjA0QUY0NjVENkE=",
            "cache-control": "no-cache",
            ]


URLSession.shared.dataTask(with: request) { (data, response, error) in
  guard error == nil else { return }

  guard let data = data, let response = response else { return }
  let yourdata = data
  print(data,response)
  // handle data
}.resume()


}
  • Related