Firstly you need this code in swift in order to parse the variables to the php file. I will show you the code and will explain it to you afterwards step by step.
Here the code for Swift:
func HttpRequest() {
let myUrl = NSURL(string: "http://yourUrl.de/yourPhpScript.php");
let request = NSMutableURLRequest(URL: myUrl!);
request.HTTPMethod = "POST";
let postString = "Message=\(textView.text)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = json {
var resultValue = parseJSON["status"] as? String
print("result: \(resultValue)")
if(resultValue=="Success")
{
// If result from php is success, do something...
}
else
{
// if result from php failed, do something...
}
dispatch_async(dispatch_get_main_queue(), {
//Display alert with confirmation.
let myAlert = UIAlertController(title: "Alert", message: "Your message", preferredStyle: UIAlertControllerStyle.Alert);
let OkAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default){ action in
}
myAlert.addAction(OkAction)
self.presentViewController(myAlert, animated: true, completion: nil);
});
}
} catch {
// report error
}
}
task.resume()
}
Lets start with the explanation:
- In the first line you have a string referring to your .php file which might be on the server
request.HTTPMethod is set to POST because you want to post something to the php file
- Now the postString: From my example there is a variable called "Message" in the php file and with the "=" you simply assign it a value which is "textView.text" in my case, you can append other variables as well by putting and "&" directly after it
- Then there is a bit of code, the request is ASYNC of course because you don't want to block your main thread, this is very important
- In the
if let parseJSON will be the values of the re-parsed values from the php script, which will be available if the ASYNC returned a value, don't put it before it won't be available
- In your php file you could simply parse back a variable named "status" to show on success or on failure and you can handle that back in swift then
Now the php file:
<?php
// If you want to connect to a server you have to do that
$servername = "";
$username = "";
$passwordServer = "";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $passwordServer, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset ($_POST["Message"]){
$YourMessageFromSwift = $_POST["Message"];
}
// do what you want using php
$returnValue["status"] = "Success";
echo json_encode($returnValue);
mysqli_close($verbindung);
?>
Explanation:
- Firstly create the connection to your server (this is optional)
- Then use isset to evaluate if the variable is passed correctly
- Remember that the
$_POST["Message"] are the same as in the swift file
- In the last step you could parse the status with json_encode
Hope this helps all of you:)