使用基本身份验证的SwiftUI API调用

kmbjn2e3  于 2023-06-21  发布在  Swift
关注(0)|答案(1)|浏览(151)

我试图从SwiftUI访问具有基本身份验证的外部API,但我不知道如何做到这一点。我已经连接到其他API而没有身份验证,一切正常。如何修改下面的代码,使其能够使用具有基本身份验证的API?谢谢你的帮助

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)
    }
}
q7solyqu

q7solyqu1#

感谢@Larme提供的信息。我已经成功连接到API。我是这么做的。

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()

相关问题