skip to Main Content

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

2

Answers


  1. import Foundation
    func ApiCall(urlString:String,completion:@escaping (_ data:Data?,_ error:Error?)->Void) {
       let url = URL(string: urlString)!
    
       var request = URLRequest(url: url)
       request.allHTTPHeaderFields = [
                "content-type": "application/json",
                "authorizetoken": "NjQzODM2N0NDNDM4NDhCNDk3RkU0NjA0QUY0NjVENkE=",
                "cache-control": "no-cache",
                ]
    //// you can write "Bearer" if you are requesting url as a user from server like its only use for you 
    ////if not only for you but for a group of users or for an app you shold only wirte the token string
    
    
    URLSession.shared.dataTask(with: request) { (data, response, error) in
      guard error == nil else { return completion(nil,error) }
    
      guard let data = data, let response = response else { return }
      let yourdata = data
      completion(data,nil)
      print(data,response)
      // handle data
    }.resume()
    
    
    }
    

    and you can use it like

    let data = ApiCall(urlString:"http:example.com") { data, error in
      if let _data = data {
     // handle your data here 
        }
      if let err = error {
     // handle your error here 
        }
    }
    
    Login or Signup to reply.
  2. You need to update your allHTTPHeaderFields

    request.allHTTPHeaderFields = [
                "content-type": "application/json",
                "authorizetoken": "Bearer NjQzODM2N0NDNDM4NDhCNDk3RkU0NjA0QUY0NjVENkE=",
                "cache-control": "no-cache",
                ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search