Brian Coleman

  • Home
  • ABOUT
  • SERVICES
  • PORTFOLIO
  • BLOG
  • Contact

Tutorial: Post to Web Server API in Swift using NSURLConnection

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)")
  1. Replace with the URL to your script, i.e. http://www.brianjcoleman.com/scripts/login.php
  2. Replace with the attributes you want to post to the script, i.e. ACTION=SAVE&NAME=Brian&EMAIL=test@brianjcoleman.com
  3. 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);
?>
Tutorial: Facebook Login in Swift using a Bridging HeaderTutorial: Calculate Age in Swift
Brian Coleman

Manager, Mobile Development at Rogers Communications with over 15 years of multifaceted experience including development, design, business analysis and project management working directly with clients in a consulting capacity throughout the full software life cycle.

July 8, 2014 Swift, Tutorialsapi, ios8, swift, tutorial
Follow Me
    
Categories
  • About Me
  • Frameworks
  • My Apps
  • News
  • Strategy
  • Swift
  • Tools
  • Tutorials
  • tvOS
  • Uncategorized
  • Videos
  • Watch
Archives
  • May 2016
  • January 2016
  • October 2015
  • July 2015
  • May 2015
  • April 2015
  • March 2015
  • November 2014
  • October 2014
  • September 2014
  • July 2014
  • June 2014
  • September 2013
  • August 2013
  • July 2013
  • June 2013
  • May 2013
  • April 2013
  • March 2013
  • February 2013
Recent Posts
  • Classix for iPhone, iPad & Apple TV
  • Tutorial: How to test your app for IPv6 compatibility
  • Tutorial: Testing SSL using Charles Proxy on an iOS Device
  • Tutorial: 3D Touch – Quick Actions in Swift
  • tvOS Tutorial: Top Shelf in Swift
Featured Apps
Classix
Sportsnet
TAGS
tutorialswiftios8iosobjective-cvideogamesstrategynewsframeworkappsmonitizefacebookwatchappleios7toolstvosios9apiprovisionsocialtutorialsbooksdesignbookiapIPv6iTunes Connect
Search
TAGS
tutorialswiftios8iosobjective-cvideogamesstrategynewsframeworkappsmonitizefacebookwatchappleios7toolstvosios9apiprovisionsocialtutorialsbooksdesignbookiapIPv6iTunes Connect
ABOUT
Brian is a Lead iOS/tvOS Developer from Toronto with over 18 years of multifaceted experience including development, design, business analysis and project management.

FOLLOW ME
    
Email Subscription
Sign up for my newsletter to receive the latest news and tutorials posted.

Enter your email address:

2023 © Brian Coleman