Brian Coleman

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

Api 2

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);
?>
July 8, 2014 Swift, Tutorialsapi, ios8, swift, tutorial

Tutorial: Create Your Own iOS Web API

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. In this tutorial we’ll walk-through how to setup a script on the web server using PHP and how to communicate with that script from within an app.

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.


You’ll notice that we are passing a parameter into the script ‘AdID’, this is needed if you would like to return different ads or if you would like to use the same script for multiple apps. Most ad APIs setup ads by zones, meaning a zone is a specific place in your app where you would like the ad to show up. Above we have setup one ad. All this script does it return a single line string back to the app “1|http://images.apple.com/home/images/promo_iphone5.png|http://www.apple.com/iphone/”. This string is broken up into 3 variables that are separated by a pipe “|” character. The first variable “1” is used as a flag to turn the ad on and off. I’ve used this to turn an interstitial ad (loading screen ad) on and off. If it’s set to 1 we’ll show the ad in the app, if it’s set to 0 we’ll hide the ad. The second variable “http://images.apple.com/home/images/promo_iphone5.png” is the link to the ad image we’re going to display in the app. You’ll want to link to an image on your server, as an example I’m linking to an image on Apple.com. Lastly, the third variable “http://www.apple.com/iphone/” is where the ad links to when a user taps on it.

Communicating to the API From Your App

Now that the server side is setup we need to get the data into our app. The best way to do this is using a framework named ASIHTTPRequest. This framework allows us to send a HTTP request to the web server and listen for a response back which we’ll parse into variables.

Download the framework from the ASIHTTPRequest documentation site.

First, you’ll need to integrate the framework into your project.
1. Download the source code from the link above.
2. Add all of the header and implementation files into your project.
4. Include the following header to the top of your implementation class:
– #import “ASIHTTPRequest.h”

Here is the header file to our implementation where the ad link, button and image are defined so we can use them globally within the implementation.

// AdViewController.h
// Ad View

#import 

@interface AdViewController : UIViewController

@property (nonatomic, strong) NSString *adLink;
@property (nonatomic, strong) IBOutlet UIView *adView;
@property (nonatomic, strong) IBOutlet UIButton *adLinkButton;
@property (nonatomic, strong) IBOutlet UIImageView *adImageView;

- (void)callAdService;
- (IBAction)adButtonPushed:(id) sender;

@end

Below is the top of our implementation where we synthesize the properties and make the call to run the API in the viewDidLoad method.

// AdViewController.m
// Ad View

#import "AdViewController.h"
#import "ASIHTTPRequest.h"

@implementation AdViewController

@synthesize adLink, adLinkButton, adImageView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self callAdService];
}

Next, include the following method into your class to post the request to your web server. Notice that we’re setting the ‘AdID’ to 1 to match the ad that we want to receive from the API that we defined above in the PHP script. The setDidFinishSelector: defines what is the name of the method that will handle the return message from the server and setDidFailSelector: the method if an error happened and we didn’t receive a response back.

-(void)callAdService{
    //this is a typical url for REST webservice, where you can specify the method that you want to call and the parameters directly with GET
    NSURL *url = [NSURL URLWithString:@"http://www.YOURWEBSERVER.com/api/adAPI.php?AdID=1"];
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    
    [request setDidFinishSelector:@selector(requestCompleted:)];
    [request setDidFailSelector:@selector(requestError:)];
    
    [request setDelegate:self];
    [request startAsynchronous];
}

Below is the method that is called when we receive the data back from the API. Remember we are expecting to receive a single string with three variables in it separated by a pipe. 1|http://images.apple.com/home/images/promo_iphone5.png|http://www.apple.com/iphone/
The string is parsed by the pipes and fed into an array. The first element being the flag to show or hide and ad, the second is the link to the hosted ad image and the third is the link once the ad is tapped. After the data is parsed into variables we check to see if the ad should be displayed, if it should be then we animate the ad up, grab the image from the URL to display it.

- (void)requestCompleted:(ASIHTTPRequest *)request
{
    NSString *responseString = [request responseString];
    NSLog(@"API Response: %@", responseString);
    
    NSArray *valueArray = [responseString componentsSeparatedByString:@"|"];
    NSString *interstitialAd = [valueArray objectAtIndex:0];
    NSString *adImage = [valueArray objectAtIndex:1];
    adLink = [valueArray objectAtIndex:2];
    
    if ([interstitialAd integerValue] == 1)
    {
        [self.view bringSubviewToFront:adView];
        adImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:interstitialAdImage]]];
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
        [UIView setAnimationBeginsFromCurrentState:YES];
        
        // The transform matrix
        if (UI_USER_INTERFACE_IDIOM() != UIUserInterfaceIdiomPad && IS_IPHONE_5) {
            CGAffineTransform transform = CGAffineTransformMakeTranslation(0, -569);
            adView.transform = transform;
        }
        else {
            CGAffineTransform transform = CGAffineTransformMakeTranslation(0, -569);
            adView.transform = transform;
        }
    }
}

To finish up the process, we need to handle two events, the click-thru and the close buttons. In the “clickAdButtonPushed” we take the “adLink” variable and open the URL in the Users browser if they click on it. If you are using analytics tracking, this is where you’ll place your tag to track the conversion of your ad. The other method “closeAdButtonPushed” will animate the ad down off the screen so the user can continue to use your application.

-(IBAction) clickAdButtonPushed:(id) sender {
    NSString *str = adLink;
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    adView.alpha = 0;
}

-(IBAction) closeAdButtonPushed:(id) sender {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationBeginsFromCurrentState:YES];
    
    // The transform matrix
    CGAffineTransform transform = CGAffineTransformMakeTranslation(0, 0);
    adView.transform = transform;
    // Commit the changes
    [UIView commitAnimations];
}
April 10, 2013 Tutorialsapi, ios, objective-c, tutorial
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