SwiftUI 问答之 如何使用 Swift 和 macOS 读取 JSON

实战问题

我可以找到一些关于如何为 iOS 读取 JSON 的信息。与 macOS 无关。当我尝试将 iOS 代码应用于 macOS 时,它给了我一个错误。例如,这适用于 iOS 但不适用于 macOS:

struct User: Codable {

let name: String

let email: String

}

class ViewController: NSViewController {

override func viewDidLoad() {

super.viewDidLoad()

let url = URL(string: "https://jsonplaceholder.typicode.com/users")!

URLSession.shared.dataTask(with: url) { data, _, _ in

if let data = data {

let users = try? JSONDecoder().decode([User].self, from: data)

print (users![0].name)

}

}.resume()

}

}

在控制台中我有一个很长的错误,最后它说: NSLocalizedDescription=A server with the specified hostname could not be found. 但这在 iOS 中有效,如果您将地址放在浏览器中,它会转到 JSON 文件。

<

查看原文