我是 Swift 的新手,正在尝试发出 HTTP 请求。我尝试了很多想法 in this Stack Overflow question ,但在 Playground 上运行时都会导致错误;我相信这是因为它们都在 Swift 1.0-2.0 中。
如何在 Swift 3 中发出 HTTP 请求?
更新 我尝试了 this answer 中提供的第一个解决方案并且,在完成 Xcode 建议的“Fix-its”后,我遇到了四个错误:
最佳答案
您的代码有几个问题:
- 默认情况下,您的应用无法连接到不安全(即 HTTP)网站。这是一项称为应用程序传输安全性的功能。您需要在应用程序的
Info.plist
文件中设置异常(exception),才能连接到 HTTP 站点。 - 这:
dataTask(urlwith: !as URL)
。你想用感叹号 (!
) 解开什么?变量名是什么?
很多类名在 Swift 2 和 3 之间发生了变化,因此您找到的那些答案可能不适用。下面是连接到 httpbin.org 的示例获取您的 IP 地址:
import PlaygroundSupport
import Foundation
let url = URL(string: "https://httpbin.org/ip")
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()
PlaygroundPage.current.needsIndefiniteExecution = true
关于swift - Swift 3 中的 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38292793/