如何在SWIFT中发出HTTP请求?我在iBooks中阅读了苹果的编程语言SWIFT,但我不知道如何用SWIFT发出http请求(类似curl)。我需要导入Obj-C类还是只需要导入默认库?还是不可能基于本机快速代码发出HTTP请求?
3 回答
ibeautiful
TA贡献1993条经验 获得超5个赞
URL
, URLRequest
URLSession
NSURLConnection
URLSession
使用 URLSession
URL
URLSessionDataTask
URLSession
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"
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
NSURLConnectionDataDelegate
在Xcode操场上进行测试
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
尚方宝剑之说
TA贡献1788条经验 获得超4个赞
1.SynchonousRequest
SWIFT 1.2
let urlPath: String = "YOUR_URL_HERE" var url: NSURL = NSURL(string: urlPath)! var request1: NSURLRequest = NSURLRequest(URL: url) var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil var dataVal: NSData = NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)! var err: NSError println(response) var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary println("Synchronous\(jsonResult)")
SWIFT 2.0+
let urlPath: String = "YOUR_URL_HERE" let url: NSURL = NSURL(string: urlPath)! let request1: NSURLRequest = NSURLRequest(URL: url) let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil do{ 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.AsynchoousRequest
SWIFT 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 in var err: NSError var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary println("Asynchronous\(jsonResult)") })
SWIFT 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 in do { if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary { print("ASynchronous\(jsonResult)") } } catch let error as NSError { print(error.localizedDescription) } })
3.与往常一样,URL连接
SWIFT 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()
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){ self.dataVal?.appendData(data)}func connectionDidFinishLoading(connection: NSURLConnection!){ var error: NSErrorPointer=nil var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: error) as NSDictionary println(jsonResult)}
SWIFT 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()
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.异地请求
SWIFT 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 Value let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding) request1.timeoutInterval = 60 request1.HTTPBody=data request1.HTTPShouldHandleCookies=false let queue:NSOperationQueue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in var err: NSError var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary println("AsSynchronous\(jsonResult)") })
SWIFT 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 Value let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding) request1.timeoutInterval = 60 request1.HTTPBody=data request1.HTTPShouldHandleCookies=false let queue:NSOperationQueue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler: { (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in do { if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary { print("ASynchronous\(jsonResult)") } } catch let error as NSError { print(error.localizedDescription) } })
5.同步索取请求
SWIFT 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 = 60 let queue:NSOperationQueue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler: { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in var err: NSError var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary println("AsSynchronous\(jsonResult)") })
SWIFT 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 in do { if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary { print("ASynchronous\(jsonResult)") } } catch let error as NSError { print(error.localizedDescription) } })
6.图像(档案)上传
SWIFT 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 want let 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 parameters body.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 Data var 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 = body let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in if error != nil { //handle error } else { let outputString : NSString = NSString(data:data!, encoding:NSUTF8StringEncoding)! print("Response:\(outputString)") } } dataTask.resume()
- 3 回答
- 0 关注
- 1872 浏览
添加回答
举报
0/150
提交
取消