Home » How - To / Tutorial » Programming » Simple Way to Connect Swift to PHP Code

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.

Swift-Programming Simple Way to Connect Swift to PHP CodeThere 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:

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:

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:

Below the above lines of code, add the following:

For you to specify the method that we are sending in, add the following code:

We then need to put together all the above, and send to the server as one. This can be done as follows:

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:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *

This site uses Akismet to reduce spam. Learn how your comment data is processed.