0

I'm trying to access from SwiftUI to an external API that has basic authentication, but I can't figure out how to do it. I have connected to other APIs without authentication and everything works correctly. How could you modify the following code to be able to use the API with basic authentication? Thanks for the help

func loadData() async {
    guard let url = URL(string: "https://urlapi/user/basicauth") else {
        print("bad URL")
        return
    }
    do {
        let (data, _) = try await URLSession.shared.data(from: url)
        users = try JSONDecoder().decode([JSONuser].self, from: data)
    } catch {
        print(error)
    }
}

Jerry Stratton
  • 3,287
  • 1
  • 22
  • 30
JuanE
  • 1
  • 2
  • This is not related to Swift UI, it's just related to Swift. What's happening with your code? What does the doc say? – Larme Jun 13 '23 at 16:11
  • Hi @loremipsum. Basic authentication is when the API uses a username and password to be able to connect and use the data it returns. In other programming languages such as Flutter or PHP they can be added as extra parameters to the connection. – JuanE Jun 13 '23 at 16:35
  • https://stackoverflow.com/questions/24379601/how-to-make-an-http-request-basic-auth-in-swift ? – Larme Jun 13 '23 at 16:55
  • @loremipsum Basic Auth is a thing, and that's what it's called: https://www.twilio.com/docs/glossary/what-is-basic-authentication – Mikaela Caron Jun 13 '23 at 20:23

1 Answers1

0

Thanks @Larme for the info. I have managed to connect to the API. Here how I did it.

import UIKit

func apiCall()
{
  guard let url = URL(string: "https://urlapi/user/basicauth") else {return}
  let username = "useapi"
  let password = "passapi"
  let loginString = String(format: "%@:%@", username, password)
  let loginData = loginString.data(using: String.Encoding.utf8)!
  let base64LoginString = loginData.base64EncodedString()

  var request = URLRequest(url: url)
  request.httpMethod = "GET"
  request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

  let task = URLSession.shared.dataTask(with: request){data, _, error in
    guard let data = data, error == nil else {return}
    do
    {
      let response = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
      print(response)
    }
    catch
    {
      print(error)
    }
  }
  task.resume()
}

apiCall()
JuanE
  • 1
  • 2