Home > Mobile >  How to implement the Bearer Token to validate the API url
How to implement the Bearer Token to validate the API url

Time:11-15

I set up the API and all, the only thing is Bearer Token I couldn't find any information about any code on how to implement it so it can validate the URL I am using as API.

do I need to create new swift file just for bearer token or I can write the code to the API swift file "the code below is api file"

static let shared = APICaller()
private let baseURL = "http://000.000.000.000:3030/api/"

private init() {}

var vehicles = [Vehicles]()
    
func getVehicles(for id: String, IMEI: Int, completed: @escaping (Result<[Vehicles],Errors>) -> Void ){
    let endpoint = baseURL   "GetVehicle/?UserIdentificationValue=346HIU4623UIHG3I3I&IMEI=216216123612"
    
    guard let url = URL(string: endpoint) else {
        completed(.failure(.invalidURL))
        return
    }
    
    let task = URLSession.shared.dataTask(with: url) { data, response, error in
        
        if let _ = error {
            completed(.failure(.unableToComplete))
            return
        }
        guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
            completed(.failure(.invalidResponse))
            return
        }
        guard let data = data else {
            completed(.failure(.invalidData))
            return
        }
        
        do {
            let decoder = JSONDecoder()
            decoder.keyDecodingStrategy = .convertFromSnakeCase
            
            self.vehicles = try JSONDecoder().decode([Vehicles].self, from: data)
            
            DispatchQueue.main.async {
                completed(.failure(.invalidData))
            }
            
        } catch {
            completed(.failure(.invalidData))
        }
    }
    task.resume()

Thanks In Advance

Also I am new to swift so I would appreciate if you can tell me my API code is correct or needs any fixes since its about receiving some car info and putting into a table view cell :)

CodePudding user response:

I have attached the request including headers in which you need to pass Bearer token like did in below code

    let headers = [
        "content-type": "application/json",
        "authorizetoken": "NjQzOPA2N0NDNDFAH4CNDk3R23F2FQUY0NjV3FFE=",
        "cache-control": "no-cache",
        ]
    
    let parameters = ["id":"123456789"] as [String : Any]
    let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])
    let request = NSMutableURLRequest(url: NSURL(string: "Your URL")! as URL,
                                      cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 120.0)
    
    request.httpMethod = "POST"
    request.allHTTPHeaderFields = headers
    request.httpBody = postData as? Data
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData
  • Related