In the past I have always used the ASIHTTPRequest third-party library to make an asynchronous request to a server. It’s been outdated for at least a year but still worked for all I needed it for. I thought I’d look for a more native approach to use in Swift instead of using a Bridging Header to import the library. Below is a simple and effective way to connect to a web API (Perl, PHP, Rails) from Swift using NSURLConnection.
Communicating to the API From Your App
let url = NSURL(string:"") let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0) request.HTTPMethod = "POST" // set Content-Type in HTTP header let boundaryConstant = "----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy"; let contentType = "multipart/form-data; boundary=" + boundaryConstant NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request) // set data var dataString = "" let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding) request.HTTPBody = requestBodyData // set content length //NSURLProtocol.setProperty(requestBodyData.length, forKey: "Content-Length", inRequest: request) var response: NSURLResponse? = nil var error: NSError? = nil let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error) let results = NSString(data:reply!, encoding:NSUTF8StringEncoding) println("API Response: \(results)")
- Replace with the URL to your script, i.e. http://www.brianjcoleman.com/scripts/login.php
- Replace with the attributes you want to post to the script, i.e. ACTION=SAVE&NAME=Brian&EMAIL=test@brianjcoleman.com
- If you are to retrieve data from the server for confirmation or you’re pulling data from the server you’ll receive that in the “results” variable
Most of the top apps in the App Store communicate with a server for one reason or another. An app may need to send user data such as game scores or currency to a global database to track rankings or currency. It may serve up dynamic content or even ads that the owner wishes to change without making an app update. All of this and more require an API (application programming interface) to communicate between the app and the web server.
Setup the PHP Web API
To start you’ll need a web server that will host the PHP script. One of the best shared hosts in the US is 1 & 1. You can host as many URLs and MySQL databases as you wish for around $100 a year. Next you need to write your PHP script that will be sending data to your app.
The code below is PHP, you can cut and paste it into a text editor and save it as adAPI.php, then upload it to your server. Be sure to set the permissions of the file on the server to 0755 to make it executable. You can do that using any FTP program and right clicking on the file and selecting “Permissions”. If they are not set correctly the app will not be able to execute the PHP script on the server and it will return an error.
id = $id; $this->image_url = $image_url; $this->url = $url; } } $myAd = new Ad(1, "image_url", "url"); echo json_encode($myAd); ?>