我正在尝试使用 Swift 4 Codable
功能来获取 JSON,但由于某种原因它会产生一个错误:
Argument type string does not conform to expected type decoder
这是我的代码:
import UIKit
struct aURL : Codable {
let title: String
let aurl: String
// let style: URLStyle
}
class SectionTableViewController: UITableViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
do {
let queue = DispatchQueue(label: "cool")
queue.async {
if let somedata = try? Data(contentsOf: URL(from: "http://json-schema.org/example/geo.json")!, options: []) {
let json = try? JSONSerialization.jsonObject(with: somedata, options: [])
print(json)
DispatchQueue.main.async {
}
}
}
} catch let error as NSError {
print("Error: \(error)")
}
}
如果我尝试使用 Xcode 建议的修复方法修复它,如图所示:
我收到这个错误:
Could not cast value of type 'Swift.String' (0x1015acf68) to 'Swift.Decoder' (0x1015ec460).
最佳答案
有一个误会。
URL
接口(interface)
init(from decoder: Decoder) throws
可以仅用于在自定义结构中,以根据给定的Decoder
创建一个URL与 init(coder
非常相似API相关类NSCoding
协议(protocol)。
在从字符串创建 URL 的上下文中,您必须使用 URL(string
URL(string: "http://json-schema.org/example/geo.json")!
这正是错误消息所说的:我期待一个 Decoder
但我得到一个String
重要提示:
从不使用同步 API 从远程 URL 加载数据 Data(contentsOF:
– 即使在异步调度队列中也不行 – 不要粗心地忽略 try?
的错误
关于swift - "Argument type string does not conform to expected type decoder"尝试使用可编码协议(protocol)获取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48342932/