如何在Swift中发出HTTP请求? [英] How do I make an HTTP request in Swift?

查看:187
本文介绍了如何在Swift中发出HTTP请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了iBooks中Apple编写的 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?

推荐答案

您可以像在Objective-C中通常使用的那样使用URLURLRequestURLSessionNSURLConnection.请注意,对于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.

初始化URL对象和URLSession中的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

首先,初始化URLURLRequest:

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:

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游乐场上尝试此代码,请将import PlaygroundSupport添加到游乐场,以及以下调用:

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

这将允许您在操场上使用异步代码.

This will allow you to use asynchronous code in playgrounds.

这篇关于如何在Swift中发出HTTP请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆