我正在构建一个检查域可用性的应用程序。现在,我正在使用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;但是,当我发出请求时,会出现如下错误:
必须指定凭据
我想知道如何解决这个问题。这是我目前的代码:
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.
}
}
答案 0 :(得分:3)
我知道这不是使用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: url!) { 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