I'm trying to understand the process of post request in xcode 8 swift 3.
I managed to post data manually by adding value into "paramString".
My question is, how to pass the data if the input data is coming from textfield?
I named it usernameTxt and passwordTxt. How to pass these value into PHP MySQL using the code below?
What would "paramString" will be if the view controller have multiple textfield input into web services?
My code so far as below
import UIKit
class ViewController: UIViewController {
@IBOutlet var usernameTxt: UITextField!
@IBOutlet var passwordTxt: UITextField!
@IBOutlet var loginButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func sendData(_ sender: Any) {
data_request("http://localhost/send.php")
}
func data_request(_ url:String)
{
let name = usernameTxt.text
let pass = passwordTxt.text
let url:NSURL = NSURL(string: url)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
let paramString = "data=" + name!
// let paramString = "data=" + name! + "data2=" + pass! //this line does not work
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest){
(data, response, error) in
guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else {
print("Error")
return
}
if let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue){
print(dataString)
}
}
task.resume()
}
}
usernameTxt.text
andpasswordTxt.text
A parameter string for a POST request must be in format
A convenient way to create the string is String Interpolation
It's good programming habit to check if the
text
properties are notnil
and not empty. Further in Swift 3 use the native structsURL
andURLRequest
.By the way Swift is not PHP. The naming convention is to use camel case.