如何在 Swift 中发出 HTTP 请求? [英] How do I make an HTTP request in Swift?
问题描述
我在 iBooks 中阅读了 Apple 的 The Programming Language Swift,但不知道如何在 Swift 中发出 HTTP 请求(类似于 cURL).我需要导入 Obj-C 类还是只需要导入默认库?还是无法基于原生 Swift 代码发出 HTTP 请求?
I read The Programming Language Swift by Apple in iBooks, but cannot figure out how to make an HTTP request (something like cURL) in Swift. Do I need to import Obj-C classes or do I just need to import default libraries? Or is it not possible to make an HTTP request based on native Swift code?
推荐答案
您可以使用 URL
、URLRequest
和 URLSession
或 NSURLConnection
就像您在 Objective-C 中通常所做的那样.请注意,对于 iOS 7.0 及更高版本,首选 URLSession
.
You can use URL
, URLRequest
and URLSession
or NSURLConnection
as you'd normally do in Objective-C. Note that for iOS 7.0 and later, URLSession
is preferred.
从 URLSession
初始化一个 URL
对象和一个 URLSessionDataTask
.然后使用 resume()
运行任务.
Initialize a URL
object and a URLSessionDataTask
from URLSession
. Then run the task with resume()
.
let url = URL(string: "http://www.stackoverflow.com")!
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
guard let data = data else { return }
print(String(data: data, encoding: .utf8)!)
}
task.resume()
使用NSURLConnection
首先,初始化一个URL
和一个URLRequest
:
let url = URL(string: "http://www.stackoverflow.com")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
然后,您可以异步加载请求:
Then, you can load the request asynchronously with:
NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main) {(response, data, error) in
guard let data = data else { return }
print(String(data: data, encoding: .utf8)!)
}
或者你可以初始化一个NSURLConnection
:
Or you can initialize an NSURLConnection
:
let connection = NSURLConnection(request: request, delegate:nil, startImmediately: true)
只需确保将您的委托设置为 nil
以外的其他内容,并使用委托方法处理收到的响应和数据.
Just make sure to set your delegate to something other than nil
and use the delegate methods to work with the response and data received.
有关详细信息,请查看 文档NSURLConnectionDataDelegate
协议
For more detail, check the documentation for the NSURLConnectionDataDelegate
protocol
如果您想在 Xcode playground 上尝试此代码,请将 import PlaygroundSupport
添加到您的 Playground 中,以及以下调用:
If you want to try this code on a Xcode playground, add import PlaygroundSupport
to your playground, as well as the following call:
PlaygroundPage.current.needsIndefiniteExecution = true
这将允许您在 Playgrounds 中使用异步代码.
This will allow you to use asynchronous code in playgrounds.
这篇关于如何在 Swift 中发出 HTTP 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!