swiftapiswiftuiurlsessionnsurlsessiondatatask

Headers not being set correctly, Swift API Call


Trying to do an API call, and have used a data task before. Now I tried the DataPublisher instead with combine. I have developed an API that needs authorisation with a specific token. Sadly the auth header doesn't seem to be initialized when I run my app.

Swift file that executes the API call

final class TransactionListViewModel: ObservableObject {
@Published var transactions: [Transaction] = []

private var cancellables = Set<AnyCancellable>()

init() {
    getTransactions()
}

func getTransactions() {
    guard let url = URL(string: "THE_URL") else {
        print("Invalid URL")
        return
    }
    
    var request = URLRequest(url: url)
    
    // Setting the HTTP Method
    request.httpMethod = "GET"
    
    // Setting the HTTP Headers
    request.setValue("application/vnd.api+json", forHTTPHeaderField: "Content-Type")
    request.setValue("application/vnd.api+json", forHTTPHeaderField: "Accept")
    
    // Set the auth Berear token
    request.setValue("Bearer THE_TOKEN_HERE", forHTTPHeaderField: "Authorization")
    
    URLSession.shared.dataTaskPublisher(for: request)
        .tryMap { (data, response) -> Data in
            guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
                dump(response)
                throw URLError(.badServerResponse)
            }
            
            return data
        }
        .decode(type: [Transaction].self, decoder: JSONDecoder())
        .receive(on: DispatchQueue.main)
        .sink { completion in
            switch completion {
            case .failure(let error):
                print("Error fetching transactions: ", error)
            case .finished:
                print("Finished fetching transactions")
            }
        } receiveValue: { [weak self] result in
            self?.transactions = result
            dump(self?.transactions)
        }
        .store(in: &cancellables)
    }
}

The error in the console

<NSHTTPURLResponse: 0x600002d9c680> { URL: THE_URL } { Status Code: 401, Headers {
    "Access-Control-Allow-Origin" =     (
        "*"
    );
    "Alt-Svc" =     (
        "h3=\":443\"; ma=2592000, h3-29=\":443\"; ma=2592000, h3-Q050=\":443\"; ma=2592000, h3-Q046=\":443\"; ma=2592000, h3-Q043=\":443\"; ma=2592000, quic=\":443\"; ma=2592000; v=\"43,46\""
    );
    "Cache-Control" =     (
        "no-cache, private"
    );
    "Content-Encoding" =     (
        br
    );
    "Content-Length" =     (
        34
    );
    "Content-Type" =     (
        "application/json"
    );
    Date =     (
        "Sun, 12 Feb 2023 17:56:51 GMT"
    );
    Server =     (
        LiteSpeed
    );
    Vary =     (
        "Accept-Encoding"
    );
    "x-powered-by" =     (
        "PHP/8.1.15"
    );
} } #0
  - super: NSURLResponse
    - super: NSObject
Error fetching transactions:  Error Domain=NSURLErrorDomain Code=-1011 "(null)"
Message from debugger: Terminated due to signal 9

As seen non of my headers are in the console output.

I Have searched around the internet without any help. What am I doing wrong?

I tried to use addValue instead of setValue. It did not work. I Have not found any other solutions on the internet.


Solution

  • Found the solution. The actual URL it self was wrong. Had to remove the last / from the URL and the status code 401 was now removed and I get 200 OK

    Before (not working) https:/www.url.com/api/task/

    Now (working) https:/www.url.com/api/task