Simple Way to Connect Swift to PHP Code
It is possible to use Swift to send some post request to a PHP script. This happens on a server. If you connect your Swift app to a PHP web service, you will achieve functionalities such as querying the database and even registering the users.
There are also many features that you can enjoy. There exist services that can help you in achieving this. Programmers without access to a PHP web service or those who cannot create one for themselves can use these services.
We will use Parse.com for this purpose. It uses HTTP (Hyper Text Transfer Protocol) request codes to determine whether the requests that you send succeeded or failed. These codes are numerous, and each is used for a specific purpose, so you can find tutorials about these online, and use the right one. We will use the code 200 which tells us that our connection succeeded, and then we will be able to succeed.
Set up a new Swift project on Xcode 6. Onto the Main.storyboard, drag a button. Link it as an IBAction to the viewController, and give it a name of your choice. The next thing is to add functionality to this button. This can be achieved by use of a function. I will call my function sendFunction. The viewController.Swift should be as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import UIKit
class ViewController: UIViewController {
func sendFunction() {
println("Button Pressed")
}
@IBAction func sendButton(sender: AnyObject) {
sendFunction()
}
override func viewDidLoad() {
super.viewDidLoad()
// add any addition setup after the view is loaded.
}
override func receivedMemWarning() {
super.receivedMemWarning()
//any resources with the ability to be created should be disposed.
}
}
|
The “Button Pressed” message will be displayed on the console line area. In case you need to be emailed when there is a post request, you can use the PHP code below:
1
2
3
4
|
$reqVar = $_POST['data'];
if (!empty($reqVar)) {
}
|
If you want to allow someone to access your server, or if you are connecting to a database, make sure that you are careful so as to avoid malicious attacks.
Posting from Swift to PHP
Declare the following two variables in your function:
1
2
|
var u: NSURL = NSURL(string: "http://url.com/path/to/file.php")!
var rqst:NSMutableURLRequest = NSMutableURLRequest(URL:url)
|
Below the above lines of code, add the following:
1
|
var bData = "data=something"
|
For you to specify the method that we are sending in, add the following code:
1
|
rqst.HTTPMethod = "POST"
|
We then need to put together all the above, and send to the server as one. This can be done as follows:
1
2
3
4
5
|
rqst.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(rqst, queue: NSOperationQueue.mainQueue()) {
(response, data, error) in
println(response)
}
|
After running the app at this time, a response will be seen in the console log. It will have the entire response.
How to Get the Status of the HTTP Code
In the above case, regardless of whether the scripts succeeds or fails, the user will be directed to the ViewController. We want to direct the user to a new ViewController if the connection exists and the script runs correctly. An if statement is the right choice here, and we should combine it with the code 200. This can be done as follows:
1
2
3
4
5
6
|
if let HTTPResponse = response as? NSHTTPURLResponse {
let sCode = HTTPResponse.statusCode
if sCode == 200 {
// Then do something.
}
}
|
You can now run your app. You now know how to post to a PHP script from Swift. We have also used a status code to check whether this went on correctly.