在 Swift 中将 cUrl 命令转换为 HTTP 请求

Convert cUrl command to HTTP Request in Swift

我正在构建一个检查域可用性的应用程序。现在,我正在使用 goDaddy API;根据 goDaddy 的说法,检查 URL 可用性的方法是通过以下 cURL 命令:

curl -X GET -H "Authorization: sso-key {API_KEY}:{API_SECRET}" "https://api.godaddy.com/v1/domains/available?domain=example.guru"

现在,我正在尝试将 cURL 命令转换为 Swift。我正在使用 Alamofire;但是,当我发出请求时,出现如下错误:

Credentials must be specified

我想知道如何解决这个问题。这是我当前的代码:

class ViewController: UIViewController {

    let key = "KEYKEYKEY"
    let secret = "SECRETSECRET"

    var headers: HTTPHeaders = [:]

    override func viewDidLoad() {
        super.viewDidLoad()

        let credential = URLCredential(user: key, password: secret, persistence: .forSession)

        Alamofire.request("https://api.godaddy.com/v1/domains/available?domain=example.guru")
            .authenticate(usingCredential: credential)
            .responseJSON { response in
                debugPrint(response)
        }

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

我知道这不是使用 Alamofire,但这是我实现它的方式。

import PlaygroundSupport
import Foundation
let key = "2s7Ymz8gu7_8XuTEeMFVmxJBLmyNNL4n8"
let secret = "8XuXAs8K37ejtYqvsEue2p"

let url = URL(string: "https://api.ote-godaddy.com/v1/domains/available?domain=example.guru&checkType=FULL")

var request = URLRequest(url: url!)

request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("sso-key \(key):\(secret)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard error == nil else {
        print(error!)
        return
    }
    guard let data = data else {
        print("Data is empty")
        return
    }

    let json = try! JSONSerialization.jsonObject(with: data, options: [])
    print(json)
}

task.resume()
PlaygroundPage.current.needsIndefiniteExecution = true