Swift 3中的HTTP请求 [英] HTTP Requests in Swift 3
问题描述
我对Swift还是相当陌生,并且正在尝试发出HTTP请求.我在这个堆栈溢出问题中尝试了许多想法 ,但是在操场上跑步时,所有这些都会导致错误;我相信这是因为它们都在Swift 1.0-2.0中.
I am fairly new to Swift, and am trying to make an HTTP request. I tried many of the ideas in this Stack Overflow question, but all caused errors when run in a playground; I believe this is because they are all in Swift 1.0-2.0.
如何在Swift 3 中发出HTTP请求?
How can I make an HTTP request in Swift 3?
更新,我尝试了此答案中介绍的第一个解决方案,并在完成Xcode的建议后修复"我遇到了四个错误:
Update I tried the first solution presented in this answer and, after completing Xcode's suggested "Fix-its" I encountered four errors:
推荐答案
您的代码有几个问题:
- 默认情况下,您的应用无法连接到不安全的(即HTTP)网站.这是一项称为应用程序传输安全性"的功能.您需要在应用程序的
Info.plist
文件中设置例外情况才能连接到HTTP网站. - 此:
dataTask(urlwith: ! as URL)
.您要用惊叹号(!
)打开什么?什么是变量名?
- By default, your app cannot connect to insecure (i.e. HTTP) site. It's a feature called App Transport Security. You need to make an exception in your app's
Info.plist
file to connect to HTTP sites. - This:
dataTask(urlwith: ! as URL)
. What are you trying to unwrap with the exclamation mark (!
)? What's the variable name?
在Swift 2和Swift 3之间,许多类名称已更改,因此您发现的答案可能不适用.以下是连接到 httpbin.org 以获得您的IP地址的示例:
A lot of class names have changed between Swift 2 and 3 so those answers you've found may not be applicable. Below is an example that connects to httpbin.org to get your IP address:
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 3中的HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!