如何在Swift中创buildHTTP请求?

我在iBooks上看了Apple的Swift编程语言,但是不知道如何在Swift中创build一个http请求(类似于CURL)。 我是否需要导入Obj-C类或只需要导入默认库? 或者是不可能做出基于本地swift代码的HTTP请求?

另一种select是提供可连接的请求/响应方法的Alamofire lib。

https://github.com/Alamofire/Alamofire

发出请求

import Alamofire Alamofire.request(.GET, "http://httpbin.org/get") 

响应处理

 Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) .response { request, response, data, error in print(request) print(response) print(error) } 

您可以像在Objective-C中通常那样使用URLURLRequestURLSessionNSURLConnection 。 请注意,对于iOS 7.0及更高版本,首选URLSession

使用URLSession

URLSession初始化URL对象和URLSession 。 然后用resume()运行任务。

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

使用NSURLConnection

首先,初始化一个URL和一个URLRequest

 let url = URL(string: "http://www.stackoverflow.com") let request = URLRequest(URL: url!) 

然后,可以通过以下方式asynchronous加载请求:

 NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in print(NSString(data: data!, encoding: NSUTF8StringEncoding)) } 

或者你可以初始化一个NSURLConnection

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

只要确保将您的委托设置nil并使用委托方法来处理收到的响应和数据。

有关更多详细信息,请查看NSURLConnectionDataDelegate协议的文档

在Xcode游乐场上testing

如果您想在Xcode游乐场上试用此代码,请将import XCPlayground添加到您的游乐场,以及以下呼叫:

 XCPSetExecutionShouldContinueIndefinitely() 

这将允许您在游乐场中使用asynchronous代码。

检查下面的代码:

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. AsynchonousRequest

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.asynchronousPOST请求

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.asynchronousGET请求

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() 

我正在使用这个人的包装,迄今为止效果很好https://github.com/daltoniam/swiftHTTP 。 到目前为止,没有大的漏洞抽象

  do { let opt = try HTTP.GET("https://google.com") opt.start { response in if 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)") } 

基本的Swift 3解决scheme

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

Swift 3数据请求使用URLSession API

  //create the url with NSURL let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")! //change the url //create the session object let session = URLSession.shared //now create the URLRequest object using the url object let request = URLRequest(url: url) //create dataTask using the session object to send data to the server let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in guard error == nil else { return } guard let data = data else { return } do { //create json object from data if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] { print(json) } } catch let error { print(error.localizedDescription) } }) task.resume() 

我已经完成HTTP请求两种方法GETPOSTJSONparsing这种方式:

on viewDidLoad()

 override func viewDidLoad() { super.viewDidLoad() makeGetRequest() makePostRequest() } func makePostRequest(){ let urlPath: String = "http://www.swiftdeveloperblog.com/http-post-example-script/" var url: NSURL = NSURL(string: urlPath)! var request: NSMutableURLRequest = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" var stringPost="firstName=James&lastName=Bond" // Key and Value let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding) request.timeoutInterval = 60 request.HTTPBody=data request.HTTPShouldHandleCookies=false let queue:NSOperationQueue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary if (jsonResult != nil) { // Success println(jsonResult) let message = jsonResult["Message"] as! NSString println(message) }else { // Failed println("Failed") } }) } func makeGetRequest(){ var url : String = "http://api.androidhive.info/contacts/" var request : NSMutableURLRequest = NSMutableURLRequest() request.URL = NSURL(string: url) request.HTTPMethod = "GET" request.timeoutInterval = 60 NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary if (jsonResult != nil) { // Success println(jsonResult) let dataArray = jsonResult["contacts"] as! NSArray; for item in dataArray { // loop through data items let obj = item as! NSDictionary for (key, value) in obj { println("Key: \(key) - Value: \(value)") let phone = obj["phone"] as! NSDictionary; let mobile = phone["mobile"] as! NSString println(mobile) let home = phone["home"] as! NSString println(home) let office = phone["office"] as! NSString println(office) } } } else { // Failed println("Failed") } }) } 

完成

您可以使用Just ,一个python-requests样式的HTTP库。

用Just发送HTTP请求的一些例子:

 // synchronous GET request with URL query a=1 let r = Just.get("https://httpbin.org/get", params:["a":1]) // asynchronous POST request with form value and file uploads Just.post( "http://justiceleauge.org/member/register", data: ["username": "barryallen", "password":"ReverseF1ashSucks"], files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)] ) { (r) if (r.ok) { /* success! */ } } 

在这两种情况下,请求r的结果都可以用类似于python-request方式访问:

 r.ok // is the response successful? r.statusCode // status code of response r.content // response body as NSData? r.text // response body as text? r.json // response body parsed by NSJSONSerielization 

你可以在这个游乐场find更多的例子

在同步模式下在操场上使用这个库是最接近Swift的cURL。

我在loginbutton点击调用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 in var strData = NSString(data: data, encoding: NSUTF8StringEncoding) var err1: NSError? var json2 = NSJSONSerialization.JSONObjectWithData(strData.dataUsingEncoding(NSUTF8StringEncoding), options: .MutableLeaves, error:&err1 ) as NSDictionary println("json2 :\(json2)") if(err) { println(err!.localizedDescription) } else { var success = json2["success"] as? Int println("Success: \(success)") } }) task.resume() } 

在这里,我已经为参数做了一个单独的字典。

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

一个简单的Swift 2.0方法来进行HTTP GET请求

HTTP请求是asynchronous的,所以您需要一种方法来从HTTP请求中获取返回的值。 这种方法使用通告,分布在两个类。

示例是使用网站http://www.example.com/handler.php?do=CheckUserJson&json=检查标识符令牌的用户名和密码。即文件名为handler.php,并在做参数来获得一个RESTful方法。;

在viewDidLoad中,我们设置NotifierObserver,设置json并调用getHTTPRequest函数。 它将通过http请求返回的参数返回到checkedUsernameAndPassword函数。

 override func viewDidLoad() { super.viewDidLoad() // setup the Notification observer to catch the result of check username and password NSNotificationCenter.defaultCenter().addObserver(self, selector: "checkedUsernameAndPassword:", name: CHECK_USERNAME_AND_PASSWORD, object: nil) let username = GlobalVariables.USER_NAME let password = GlobalVariables.PASSWORD // check username and password if let jsonString = Utility.checkUsernameAndPasswordJson(username, password:password){ print("json string returned = \(jsonString)") let url = CHECKUSERJSON+jsonString // CHECKUSERJSON = http://www.example.com/handler.php?do=CheckUserJson&json= // jsonString = {\"username\":\"demo\",\"password\":\"demo\"}" // the php script handles a json request and returns a string identifier Utility.getHTTPRequest(url,notifierId: CHECK_USERNAME_AND_PASSWORD) // the returned identifier is sent to the checkedUsernaeAndPassword function when it becomes availabel. } } 

在Utility.swift中有两个静态函数来编码json然后执行HTTP调用。

  static func checkUsernameAndPasswordJson(username: String, password: String) -> String?{ let para:NSMutableDictionary = NSMutableDictionary() para.setValue("demo", forKey: "username") para.setValue("demo", forKey: "password") let jsonData: NSData do{ jsonData = try NSJSONSerialization.dataWithJSONObject(para, options: NSJSONWritingOptions()) let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String return jsonString } catch _ { print ("UH OOO") return nil } } 

和Http请求

  static func getHTTPRequest (url:String , notifierId: String) -> Void{ let urlString = url let config = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: config, delegate: nil, delegateQueue: nil) let safeURL = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! if let url = NSURL(string: safeURL){ let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "GET" request.timeoutInterval = 60 let taskData = session.dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in if (data != nil) { let result = NSString(data: data! , encoding: NSUTF8StringEncoding) sendNotification (notifierId, message: String(result), num: 0) }else{ sendNotification (notifierId, message: String(UTF8String: nil), num: -1) } }) taskData.resume() }else{ print("bad urlString = \(urlString)") } } 

sendNotification函数完成圆圈。 请注意,在Observer中,select器string的末尾有一个“:”。 这允许通知在userInfo中携带有效载荷。 我给这个String和一个Int。

  static func sendNotification (key: String, message:String?, num: Int?){ NSNotificationCenter.defaultCenter().postNotificationName( key, object: nil, userInfo: (["message": message!, "num": "\(num!)"]) ) } 

请注意,使用HTTP是oldFashioned,更喜欢HTTPS请参阅如何加载在iOS 9中启用App Transport Security的HTTP URL?

  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 = postData request.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 NSDictionary let 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 NSMutableArray self.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") } 

它肯定会帮助你

//这是一个适合我的例子

//使用键值向服务器发送请求的Swift函数

 func insertRecords() { let usrID = txtID.text let checkin = lblInOut.text let comment = txtComment.text // The address of the web service let urlString = "http://your_url/checkInOut_post.php" // These are the keys that your are sending as part of the post request let keyValues = "id=\(usrID)&inout=\(checkin)&comment=\(comment)" // 1 - Create the session by getting the configuration and then // creating the session let config = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: config, delegate: nil, delegateQueue: nil) // 2 - Create the URL Object if let url = NSURL(string: urlString){ // 3 - Create the Request Object var request = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" // set the key values request.HTTPBody = keyValues.dataUsingEncoding(NSUTF8StringEncoding); // 4 - execute the request let taskData = session.dataTaskWithRequest(request, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in println("\(data)") // 5 - Do something with the Data back if (data != nil) { // we got some data back println("\(data)") let result = NSString(data: data , encoding: NSUTF8StringEncoding) println("\(result)") if result == "OK" { let a = UIAlertView(title: "OK", message: "Attendece has been recorded", delegate: nil, cancelButtonTitle: "OK") println("\(result)") dispatch_async(dispatch_get_main_queue()) { a.show() } } else { // display error and do something else } } else { // we got an error println("Error getting stores :\(error.localizedDescription)") } }) taskData.resume() } } 

PHP代码来获取关键值

$ empID = $ _POST ['id'];

$ inOut = $ _POST ['inout'];

$ comment = $ _POST ['comment'];