当我试图在Linux上使用Swift访问牛津字典API时,遇到了障碍。可能是我的错误,但我无法确定是什么。此时,我怀疑它与基础操作系统有关。请考虑以下Bash代码:
curl -X GET --header 'Accept: text/plain' --header 'app_id: 8a7dd147' --header 'app_key: 7e7d022fbce6d8d4523eac3baa5bd04c' 'https://od-api.oxforddictionaries.com/api/v1/entries/en/ace'
这将返回Ace单词的JSON数据。现在,在Ubuntu 18.04上,我尝试执行以下操作:
import Foundation
//var request = URLRequest(url: URL(string: "https://od-api.oxforddictionaries.com/api/v1/entries/en/love")!)
// TODO: replace with your own app id and app key
let appId = "8a7dd147"
let appKey = "7e7d022fbce6d8d4523eac3baa5bd04c"
let language = "en"
let word = "Ace"
let word_id = word.lowercased() //word id is case sensitive and lowercase is required
let url = URL(string: "https://od-api.oxforddictionaries.com/api/v1/entries/en/love")! // \(language)/\(word_id)")!
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(appId, forHTTPHeaderField: "app_id")
request.addValue(appKey, forHTTPHeaderField: "app_key")
//request.addValue("application/json", forHTTPHeaderField: "Content-Type")
print("passed request addValue")
let session = URLSession.shared
_ = session.dataTask(with: request, completionHandler: { data, response, error in
if let response = response,
let data = data,
let jsonData = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) {
print("about to give you a response")
print(response)
print(jsonData)
} else {
print(error)
print(NSString.init(data: data!, encoding: String.Encoding.utf8.rawValue))
}
}).resume()
或者以下内容:
import Foundation
let params: [String: String] = ["app_id": "8a7dd147", "app_key": "7e7d022fbce6d8d4523eac3baa5bd04c"]
var request = URLRequest(url: URL(string: "https://od-api.oxforddictionaries.com/api/v1/entries/en/love")!)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("8a7dd147", forHTTPHeaderField: "app_id")
request.addValue("7e7d022fbce6d8d4523eac3baa5bd04c", forHTTPHeaderField: "app_key")
URLSession.shared.dataTask(with: request, completionHandler: { data, response, error -> Void in
print(response!)
do {
let json = try JSONSerialization.jsonObject(with: data!)
print(json)
print("we did it!")
} catch {
print("error")
}
}).resume()
//task.resume()
但是没有返回单词“爱”的json信息。我一直在尝试调试,但无法弄清楚问题出在哪里。
- 这是否与操作系统有关,因此是一个错误?有人能够在MacOS上进行测试吗?或者我漏掉了什么?
sleep(10)
以允许程序结束前等待10秒钟时,它就有结果了。因此,如果您将其嵌入用于创建Web服务或后端的代码中,则应尝试应用异步编程(在响应事件而不是执行其他操作时进行响应)。如果您只是制作概念验证,则可以使用Data(contentsOf:)
替换URLSession以同步加载,或通过任何安全手段等待结果。 - user9335240