HTTP Get API 调用总是失败 "NSLocalizedDescription=A server with the specified hostname could not be found"

HTTP Get API call always fails "NSLocalizedDescription=A server with the specified hostname could not be found"

我在 visual studio 本地创建了一个 ASP.NET 核心网站 api,我是 运行,我可以在 Safari 中浏览到它并测试了API 使用邮递员。

当我在我的 MacOS 应用程序中使用以下 swift 代码时:

    let url = URL(string: "http://localhost:5000/api/values")

    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()

它总是因错误而失败

NSLocalizedDescription=A server with the specified hostname could not be found.

我是否必须更改一些设置,以便我的应用程序可以向 API 发出 Http 请求?

谢谢

您可能已经想出了一个解决方案或解决问题的方法,但是由于我在遇到这个问题时遇到了同样的问题,所以无论如何我都会提供我的答案,以防其他人发现这个问题。

对我来说,问题是 MacOS 应用程序无法连接到互联网,因为它会自动 运行 在应用程序沙箱中。解决方案是将 "Outgoing Connections" 添加到应用程序功能中。请参见下面的屏幕截图。