gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 14:55:10 24 4
gpt4 key购买 nike

我已经创建了一个 ASP.NET Core web api,我在 visual studio 中本地运行它,我可以在 Safari 中浏览到它并使用 postman 测试该 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 应用程序无法连接到互联网,因为它会自动在应用程序沙箱中运行。解决方案是向应用程序功能添加“传出连接”。请参见下面的屏幕截图。

enter image description here

关于swift - HTTP Get API 调用总是失败 "NSLocalizedDescription=A server with the specified hostname could not be found",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49458771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com