Fetch data from server using URLSession(New)

1 day ago 3
ARTICLE AD BOX

// MARK: - With token or without token APIManager Class.

I am trying to create a reusable API manager in Swift that can handle both authenticated (with token) and non-authenticated API requests.

I wrote a common method that accepts a URL and token. If the token is available, it should attach it in the Authorization header, otherwise it should work without token.

However, I am not sure if this is the correct or best practice approach. Also, I want to confirm:

Is it fine to use a single method for both cases?

Should I handle token differently?

Is my completion handler structure correct?

Here is my implementation:

class APIManager { static let shared = APIManager() private init(){} typealias completion = ((Data?,Any?) -> ()) // MARK: - YE method jo token pr v kam krega , without token pr v func newPostRequest(url:String, token : String , completionHandler : @escaping completion) { guard let url = URL(string: url) else { print("Invalid URL") return } var request = URLRequest(url: url) request.httpMethod = "GET" request.setValue("application/json", forHTTPHeaderField: "Content-Type") if !token.isEmpty{ request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") } else { print("invalid Token") } URLSession.shared.dataTask(with: request){data,response,error in DispatchQueue.main.async { if let error = error { print(error.localizedDescription) completionHandler(nil,error) return } guard let data = data else{ print("Invalid data") completionHandler(nil,nil) return } completionHandler(data,nil) } }.resume() } }
Read Entire Article