本文翻译自:How to make an HTTP request in Swift?

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. 我在iBooks中阅读了Apple的The Programming Language Swift,但无法弄清楚如何在Swift中发出http请求(例如CURL)。 Do I need to import Obj-C classes or do I just need to import default libraries? 我需要导入Obj-C类还是只需要导入默认库? Or is it not possible to make an HTTP request based on native swift code? 还是无法基于本机快速代码发出HTTP请求?


#1楼

参考:https://stackoom.com/question/1clh8/如何在Swift中发出HTTP请求


#2楼

You can use URL , URLRequest and URLSession or NSURLConnection as you'd normally do in Objective-C. 您可以像在Objective-C中通常那样使用URLURLRequestURLSessionNSURLConnection Note that for iOS 7.0 and later, URLSession is preferred. 请注意,对于iOS 7.0和更高版本, URLSession是首选。

Using URLSession 使用URLSession

Initialize a URL object and a URLSessionDataTask from URLSession . 初始化一个URL对象和URLSessionDataTaskURLSession Then run the task with resume() . 然后使用resume()运行任务。

let url = URL(string: "http://www.stackoverflow.com")!let task = URLSession.shared.dataTask(with: url) {(data, response, error) inguard let data = data else { return }print(String(data: data, encoding: .utf8)!)
}task.resume()

Using NSURLConnection 使用NSURLConnection

First, initialize a URL and a URLRequest : 首先,初始化一个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) inguard let data = data else { return }print(String(data: data, encoding: .utf8)!)
}

Or you can initialize an NSURLConnection : 或者,您可以初始化NSURLConnection

let connection = NSURLConnection(request: request, delegate:nil, startImmediately: true)

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. 只要确保将您的委托设置为nil以外的其他值,并使用委托方法来处理响应和接收到的数据即可。

For more detail, check the documentation for the NSURLConnectionDataDelegate protocol 有关更多详细信息,请查看有关NSURLConnectionDataDelegate协议的文档。

Testing on an Xcode playground 在Xcode游乐场进行测试

If you want to try this code on a Xcode playground, add import PlaygroundSupport to your playground, as well as the following call: 如果要在Xcode游乐场上尝试此代码,请将import PlaygroundSupport添加到游乐场,以及以下调用:

PlaygroundPage.current.needsIndefiniteExecution = true

This will allow you to use asynchronous code in playgrounds. 这将允许您在操场上使用异步代码。


#3楼

I am using this guy's wrapper with good results so far https://github.com/daltoniam/swiftHTTP . 到目前为止,我正在使用这个家伙的包装器,效果很好https://github.com/daltoniam/swiftHTTP 。 No big leaky abstractions so far 到目前为止,没有大的泄漏抽象

Example

    do {let opt = try HTTP.GET("https://google.com")opt.start { response inif let err = response.error {print("error: \(err.localizedDescription)")return //also notify app of failure as needed}print("opt finished: \(response.description)")//print("data is: \(response.data)") access the response of the data with response.data}} catch let error {print("got an error creating the request: \(error)")}

#4楼

 var post:NSString = "api=myposts&userid=\(uid)&page_no=0&limit_no=10"NSLog("PostData: %@",post);var url1:NSURL = NSURL(string: url)!var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!var postLength:NSString = String( postData.length )var request:NSMutableURLRequest = NSMutableURLRequest(URL: url1)request.HTTPMethod = "POST"request.HTTPBody = postDatarequest.setValue(postLength, forHTTPHeaderField: "Content-Length")request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")request.setValue("application/json", forHTTPHeaderField: "Accept")var reponseError: NSError?var response: NSURLResponse?var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)if ( urlData != nil ) {let res = response as NSHTTPURLResponse!;NSLog("Response code: %ld", res.statusCode);if (res.statusCode >= 200 && res.statusCode < 300){var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!NSLog("Response ==> %@", responseData);var error: NSError?let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionarylet success:NSInteger = jsonData.valueForKey("error") as NSInteger//[jsonData[@"success"] integerValue];NSLog("Success: %ld", success);if(success == 0){NSLog("Login SUCCESS");self.dataArr = jsonData.valueForKey("data") as NSMutableArrayself.table.reloadData()} else {NSLog("Login failed1");ZAActivityBar.showErrorWithStatus("error", forAction: "Action2")}} else {NSLog("Login failed2");ZAActivityBar.showErrorWithStatus("error", forAction: "Action2")}} else {NSLog("Login failed3");ZAActivityBar.showErrorWithStatus("error", forAction: "Action2")
}

it will help you surely 它一定会帮助你


#5楼

I am calling the json on login button click 我正在调用登录按钮上的json单击

@IBAction func loginClicked(sender : AnyObject) {var request = NSMutableURLRequest(URL: NSURL(string: kLoginURL)) // Here, kLogin contains the Login API.var session = NSURLSession.sharedSession()request.HTTPMethod = "POST"var err: NSError?request.HTTPBody = NSJSONSerialization.dataWithJSONObject(self.criteriaDic(), options: nil, error: &err) // This Line fills the web service with required parameters.request.addValue("application/json", forHTTPHeaderField: "Content-Type")request.addValue("application/json", forHTTPHeaderField: "Accept")var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void invar strData = NSString(data: data, encoding: NSUTF8StringEncoding)var err1: NSError?var json2 = NSJSONSerialization.JSONObjectWithData(strData.dataUsingEncoding(NSUTF8StringEncoding), options: .MutableLeaves, error:&err1 ) as NSDictionaryprintln("json2 :\(json2)")if(err) {println(err!.localizedDescription)}else {var success = json2["success"] as? Intprintln("Success: \(success)")}})task.resume()
}

Here, I have made a seperate dictionary for the parameters. 在这里,我为参数制作了单独的字典。

var params = ["format":"json", "MobileType":"IOS","MIN":"f8d16d98ad12acdbbe1de647414495ec","UserName":emailTxtField.text,"PWD":passwordTxtField.text,"SigninVia":"SH"]as NSDictionaryreturn params
}// You can add your own sets of parameter here.

#6楼

Check Below Codes : 检查以下代码:

1. SynchonousRequest 1. SynchonousRequest

Swift 1.2 斯威夫特1.2

    let urlPath: String = "YOUR_URL_HERE"var url: NSURL = NSURL(string: urlPath)!var request1: NSURLRequest = NSURLRequest(URL: url)var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nilvar dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!var err: NSErrorprintln(response)var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionaryprintln("Synchronous\(jsonResult)")

Swift 2.0 + 迅捷2.0 +

let urlPath: String = "YOUR_URL_HERE"let url: NSURL = NSURL(string: urlPath)!let request1: NSURLRequest = NSURLRequest(URL: url)let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nildo{let dataVal = try NSURLConnection.sendSynchronousRequest(request1, returningResponse: response)print(response)do {if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {print("Synchronous\(jsonResult)")}} catch let error as NSError {print(error.localizedDescription)}}catch let error as NSError{print(error.localizedDescription)}

2. AsynchonousRequest 2. AsynchonousRequest

Swift 1.2 斯威夫特1.2

let urlPath: String = "YOUR_URL_HERE"var url: NSURL = NSURL(string: urlPath)!var request1: NSURLRequest = NSURLRequest(URL: url)let queue:NSOperationQueue = NSOperationQueue()NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void invar err: NSErrorvar jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionaryprintln("Asynchronous\(jsonResult)")})

Swift 2.0 + 迅捷2.0 +

let urlPath: String = "YOUR_URL_HERE"let url: NSURL = NSURL(string: urlPath)!let request1: NSURLRequest = NSURLRequest(URL: url)let queue:NSOperationQueue = NSOperationQueue()NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void indo {if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {print("ASynchronous\(jsonResult)")}} catch let error as NSError {print(error.localizedDescription)}})

3. As usual URL connection 3.照常URL连接

Swift 1.2 斯威夫特1.2

    var dataVal = NSMutableData()let urlPath: String = "YOUR URL HERE"var url: NSURL = NSURL(string: urlPath)!var request: NSURLRequest = NSURLRequest(URL: url)var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!connection.start()

Then 然后

 func connection(connection: NSURLConnection!, didReceiveData data: NSData!){self.dataVal?.appendData(data)
}func connectionDidFinishLoading(connection: NSURLConnection!)
{var error: NSErrorPointer=nilvar jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: error) as NSDictionaryprintln(jsonResult)}

Swift 2.0 + 迅捷2.0 +

   var dataVal = NSMutableData()let urlPath: String = "YOUR URL HERE"var url: NSURL = NSURL(string: urlPath)!var request: NSURLRequest = NSURLRequest(URL: url)var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!connection.start()

Then 然后

func connection(connection: NSURLConnection!, didReceiveData data: NSData!){dataVal.appendData(data)
}func connectionDidFinishLoading(connection: NSURLConnection!)
{do {if let jsonResult = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {print(jsonResult)}} catch let error as NSError {print(error.localizedDescription)}}

4. Asynchonous POST Request 4.异步POST请求

Swift 1.2 斯威夫特1.2

    let urlPath: String = "YOUR URL HERE"var url: NSURL = NSURL(string: urlPath)!var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)request1.HTTPMethod = "POST"var stringPost="deviceToken=123456" // Key and Valuelet data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)request1.timeoutInterval = 60request1.HTTPBody=datarequest1.HTTPShouldHandleCookies=falselet queue:NSOperationQueue = NSOperationQueue()NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void invar err: NSErrorvar jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionaryprintln("AsSynchronous\(jsonResult)")})

Swift 2.0 + 迅捷2.0 +

let urlPath: String = "YOUR URL HERE"let url: NSURL = NSURL(string: urlPath)!let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)request1.HTTPMethod = "POST"let stringPost="deviceToken=123456" // Key and Valuelet data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)request1.timeoutInterval = 60request1.HTTPBody=datarequest1.HTTPShouldHandleCookies=falselet queue:NSOperationQueue = NSOperationQueue()NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void indo {if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {print("ASynchronous\(jsonResult)")}} catch let error as NSError {print(error.localizedDescription)}})

5. Asynchonous GET Request 5.异步GET请求

Swift 1.2 斯威夫特1.2

    let urlPath: String = "YOUR URL HERE"var url: NSURL = NSURL(string: urlPath)!var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)request1.HTTPMethod = "GET"request1.timeoutInterval = 60let queue:NSOperationQueue = NSOperationQueue()NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void invar err: NSErrorvar jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionaryprintln("AsSynchronous\(jsonResult)")})

Swift 2.0 + 迅捷2.0 +

let urlPath: String = "YOUR URL HERE"let url: NSURL = NSURL(string: urlPath)!let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)request1.HTTPMethod = "GET"let queue:NSOperationQueue = NSOperationQueue()NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void indo {if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {print("ASynchronous\(jsonResult)")}} catch let error as NSError {print(error.localizedDescription)}})

6. Image(File) Upload 6.图片(文件)上传

Swift 2.0 + 迅捷2.0 +

  let mainURL = "YOUR_URL_HERE"let url = NSURL(string: mainURL)let request = NSMutableURLRequest(URL: url!)let boundary = "78876565564454554547676"request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")request.HTTPMethod = "POST" // POST OR PUT What you wantlet session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)let imageData = UIImageJPEGRepresentation(UIImage(named: "Test.jpeg")!, 1)var body = NSMutableData()body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)// Append your parametersbody.appendData("Content-Disposition: form-data; name=\"name\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)body.appendData("PREMKUMAR\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)body.appendData("Content-Disposition: form-data; name=\"description\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)body.appendData("IOS_DEVELOPER\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)// Append your Image/File Datavar imageNameval = "HELLO.jpg"body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)body.appendData("Content-Disposition: form-data; name=\"profile_photo\"; filename=\"\(imageNameval)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)body.appendData(imageData!)body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)request.HTTPBody = bodylet dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void inif error != nil {//handle error}else {let outputString : NSString = NSString(data:data!, encoding:NSUTF8StringEncoding)!print("Response:\(outputString)")}}dataTask.resume()

如何在Swift中发出HTTP请求?相关推荐

  1. 如何在javascript中发出http请求?

    在 JavaScript 中,可以使用内部设置的XMLHttpRequest对象或fetchAPI 发出 HTTP 请求. 使用 XMLHttpRequest 对图像发出 HTTP 请求 以下是使用 ...

  2. 如何在Swift中串联或合并数组?

    本文翻译自:How do I concatenate or merge arrays in Swift? If there are two arrays created in swift like t ...

  3. Javasc中发出HTTP请求最常用的方法

    JavaScript具有很好的模块和方法来发送可用于从服务器端资源发送或接收数据的HTTP请求.在本文中,我们将介绍一些在JavaScript中发出HTTP请求的流行方法. Ajax Ajax是发出异 ...

  4. accept标头 php,如何在PHP中读取任何请求标头

    如何在PHP中读取任何请求标头 我应该如何阅读PHP中的任何标题? 例如,自定义标头:X-Requested-With. Sabya asked 2019-02-28T12:09:45Z 14个解决方 ...

  5. 如何在Swift中使用CoreData设置有用的自动完成UITextField

    by Emrick Sinitambirivoutin 由Emrick Sinitambirivoutin 如何在Swift中使用CoreData设置有用的自动完成UITextField (How t ...

  6. 浅层学习与深层学习_深层副本与浅层副本-以及如何在Swift中使用它们

    浅层学习与深层学习 by Payal Gupta 通过Payal Gupta 深层副本与浅层副本-以及如何在Swift中使用它们 (Deep copy vs. shallow copy - and h ...

  7. 如何在 Swift 中进行错误处理

    作者:Olivier Halligon,原文链接,原文日期:2015-12-17 译者:JackAlan:校对:靛青K:定稿:Channe 今天的文章讲解如何在 Swift 中进行错误处理. 说实话, ...

  8. 如何在Swift中创建漂亮的iOS图表

    通过图形和图表呈现数据是当今移动应用程序最显着的特征之一.iOS图表使应用程序看起来更漂亮,更有吸引力. 在本教程中,我们将向您展示如何使用代码示例在Swift中实现我们的iOS图表.我们将看一下Sw ...

  9. Javascript 中发出 HTTP 请求

    要在 JavaScript 中发出 HTTP 请求,您可以使用 XMLHttpRequest 对象或 fetch() 函数. 下面是使用 XMLHttpRequest 发出 GET 请求的示例: co ...

最新文章

  1. vue的插槽slot
  2. 华大 MCU 之一 HC32F460 替换 STM32F411 移植记录
  3. 面向对象进阶-反射(二)重要知识点
  4. win7桌面计算机没了,win7系统桌面的计算机图标没了的解决方法
  5. 查看loadrunner代码行号
  6. ASP.NET MVC 3—一切的开始MvcHandler、MvcHttpHandler
  7. javascript 基础之事件(event)-------1
  8. 测试中存在的弊端及改进建议(面试时会被问到)
  9. 算法图解——の——二分查找【附带pdf下载链接】
  10. Win1909+vs2019+Windows 10 WDK 2004(10.0.19041.1) + Windows 10 SDK 2004(10.0.19041.1)环境搭建
  11. 【情商 为什么情商比智商更重要】阅读笔记
  12. VS2003 搜索直接导致卡死问题
  13. STM32单片机基础知识总结(一)
  14. 删除顺序表中区间内的元素
  15. echarts自定义legend图例和tooltip默认提示文字
  16. Microsoft 365独家安全解决方案
  17. SAS学习(8)——自定义proc means的数据导出
  18. 微软新版edge浏览器如何开启画中画模式
  19. 手机游戏盗版现状与保护方案研究分析
  20. [多校联考-初级]徒步旅行

热门文章

  1. Incorrect string value: '\xE8\x8B\x8F\xE6\x99\xA8...' for column 'user_name' at row 1
  2. 清除Linux和window等系统的DNS缓存的命令
  3. golang 学习心得一(开发环境搭建过程中一些坑)
  4. cacti-0.8.8a那点儿事
  5. 两台XP系统电脑用双网卡共享上网操作
  6. 配置Https 和 HSTS
  7. App installation failed (A valid provisioning profile for this executable was not found)
  8. vue中使用window.open会在url前自动添加本地服务器的地址bug修复
  9. string 常用函数
  10. angularJS指令