StrikeIron Blog

Integrate a REST API into an iPhone App in less than 15 minutes

Posted by Justin Helmig on Wed, Jul 17, 2013

API availability is growing exponentially. We see this trend as an artifact of two main industry drivers, the growth in mobile applications and the opening of enterprise SaaS and on-premise applications.

Web APIs provide an easy, platform independent, way to allow mobile applications to consume data and present it to the user in a smartphone or tablet optimized experience.

This tutorial walks through consuming a REST API in iOS. In this tutorial, we will use StrikeIron’s Email Verification Plus Hygiene service. You can sign up for a free trial Email Verification Plus Hygiene here. This tutorial assumes you are proficient in Objective-C and have written basic iPhone applications. If you would like more information on either, Apple has an excellent Objective-C introduction and a getting started with iPhone developer tutorial.

Are you creating APIs for your organization? What buying criteria should you use when evaluating API management vendors? Download this guide for what you should know before beginning your search for an API management solution.

Get the API Management Buyers' Guide

1) Create the application

This application will consist of a single view for the user to enter an email address and click the submit button. When the user clicks the submit button, we will display a message indicating if the email address is valid or invalid. In a real application, if the email address is valid, you would likely proceed to the application or a thank you page.

First we will create a single view application called WebAPITutorial. In XCode, select File | New | Project. Select "Single View Application" and click Next.

On the options step, enter the following information and click Next:

Product Name: WebAPITutorial
Organization Name: <Your Organization>
Company Identifier: <Your Company Identifier>
Class Prefix: WebAPITutorial
Devices: iPhone
Use Storyboards: <Checked>
Use Automatic Reference Counting: <Checked>
Include Unit Tests: <Unchecked>

Starting with a iPhone REST API 

Select the path where you would like your project and click Create.

2) Setup the User Interface and Structural Code:

Add the controls for the single view application. In the left project view, click the MainStoryboard.storyboard item.

iOS View - REST API 

You should now see a blank view controller in the middle pane. We will add four UI controls to this view: two labels, one text box, and one button. In the bottom right hand corner of XCode, click the Objects dropdown and select Cocoa Touch Storyboard | Controls. (Note: If you do not see the Objects List, make sure the Utilities View is displayed by clicking the button on the top right hand corner of XCode that looks likeutilities icon )

iOS view 

In the controls list in the bottom right hand corner of XCode, drag the two Labels (one Text Field and one Rounded Rect Button) to the view controller canvas as seen below. 

Note: Make sure to stretch the labels to the width of the Text Field.

Labels for REST API

Next, we are going to set the Attributes for each element. First, make sure the Attributes view is open by clicking on the Attributes inspector (under the View menu at the top of XCode).

Set the following attributes for each element:

The Top Label:
Text: Enter Email Address 
The Text Field:
Keyboard: E-mail Address
Return Key: Done

The Label under the Text Field:
Text: (blank)
Alignment: Centered

The Rounded Rect Button:
Text: Submit

We are now going to connect the UI components to the Controller. First click the Assistance Editor button which is on the top right hand side of XCode and looks like assistance icon (Tip: You may want to turn off the Utilities view if your XCode window is too cluttered) 

Click the Rounded Rect Button. While holding down the Control key, drag to the line under "@interface WebAPITutorial View Controler…" You should now get a pop-up box. Change Connection to Action and enter "verifyEmail" as the Name as seen below. Click Connect.

Verify Email outlet 

Create the outlet for the Text Field by Control-Dragging the Text Field as you did above. In the pop-up, enter "emailAddress" as the Name.

Email Address Outlet

Create the outlet for the Label under the text box we will use to display the return value from the API call to the email verification API. Note that we removed the label's default text so control-click under the text box to grab the label. Enter "verificationResults" as the Name:

verification results outlet 

Finally, we will create the delegate to handle when the user taps the Done button on the keyboard after they enter their email address. Control-drag from the Text Field to the yellow circle under the view canvas. Select Outlets | delegate from the pop-up box.

iOS view

Next we are going to add the structural code. Open the WebAPITutorialViewControl.h file.

Update the interface declaration line to implement the UITextFieldDelegate protocol. It should now read:

Create the property that will hold the email address that the user entered. Just before the @end statement, add the following property.

Open the WebAPITutorialViewController.m file and directly under the @implementation WebAPITutorialViewController line, add the following:

Finally, add the following delegate method to enable the keyboard to dismiss properly in the WebAPITutorialViewController.m file.

Your application UI and structure are now done. You should be able to run your application and enter an email address but that’s about it. In the next sections, we will add the call to the REST web service and display the result to the user.

3) Invoking the API Call:

We will be calling the VerifyEmail operation on the Email Verification Plus Hygiene Web API. The REST call looks like the following:<StrikeIron User ID>&LicenseInfo.RegisteredUser.Password=<StrikeIron Password>&VerifyEmail.Email=<Email Address To Verify>&VerifyEmail.Timeout=<Time Out>&VerifyEmail.OptionalSourceId=<optional ID tag that is passed through>

We will be making the API call asynchronously, which is always a good practice since the user interface will not be blocked while the call is being made. This is especially important in mobile devices which may drop network connections. We will be implementing the delegate protocol for the NSURLConnection class.

We want to add a property and instance variable to the WebAPITutorialViewController definition, as well as the NSURLConnectionDelegate declaration. Open the WebAPITutorialViewController.h file and add the NSURLConnectionDelegate to the interface declaration and the apiReturnXMLData property:

Open the WebAPITutorialViewController.m file and navigate to the verifyEmail method (remember, this method will be called when the user touches the Submit button).

First, let's store the email address that the user entered with the following line

Next, make sure the label that will display the result of the API call is blank with the following line:

We are going to declare a variable with the REST API call but first, you will need to declare two constants at the top of the file just above the "@interface WebAPITutorialViewControllers" for your StrikeIron UserID and Password (if you don’t have one, sign up for a free email verification trial).

Now back in the verifyEmail method, add the following line to create a string with the REST API request including the UserID, Password and email address to check filled in.

Create and initialize the NSURL and NSURLRequest objects that are required to assemble the API call.

Since we are going to call the REST API asynchronously, we need to make sure that if we already have an outstanding API call, we cancel it. This will occur if the user taps the Submit button multiple times in a row before the API has returned. The connection is stored in the variable "currentConnection."

We are now ready to start the API call by creating a NSURLConnection object and initializing with the REST API call. We also initialize the apiReturnXMLData to receive the data that is returned by the API call.

Your verifyEmail method should now look like this:

Notice we set the WebAPITutorialViewController class as the delegate for the NSURLConnection object. We will be need to implement four delegate methods, didReceiveResponse, didReceiveData, didFailWithError, and connectionDidFinishLoading.

didReceiveResponse is called when there is return data. It may be called multiple times for a connection and you should reset the data if it is.

didReceiveData is called when some or all of the data from the API call is returned. We will append the data to the apiReturnXMLData instance variable.

didFailWithError is called when there is a terminal error. There will be no other method calls on this connection if it is received. In this case, we are just going to log the error.

Finally, the connectionDidFinishLoading method is called when the call is complete and all data has been received. We will parse the return data from this method. For now, just create the empty method.

We have now completed the API call and response. As you can see, it is very simple to make API calls from iOS. In the next section, we will parse and display the results. 

4) Parsing the Results:

Now that we have completed the API call and have the response stored in an instance variable, we can parse the results. Fortunately, the iOS SDK includes several options for parsing XML. The parser we will use is NSXMLParser.

As with the API call and return, we must implement several delegate methods. Open the WebAPITutorialViewController.h file. Add the following NSXMLParserDelegate to the interface declaration: 

We will also declare instance variables for the XML parser and the return values that we are going to use to hold the information we are parsing. The class declaration should now looks like. 

Next we are going to implement four delegate methods for the parser. didStartElement is called each time an element tag is encountered. Once in an element, the charaters are passed to the foundCharaters method. didEndElement is called when the element tag is closed. Finally we will implement the parserDidEndDocument which is called when the document parsing is completed.

For didStartElement, we will first check and see if there is an error. If so, we will just print out a message and let the user continue the process. We will then check to see if the element is StatusNbr or HygieneResult. If so, we will set a instance variable to maintain state between the methods calls. It will indicate to the foundCharacters method which element we are currently in.

The method source is below.

Next we will implement the foundCharacters method. We will see if we are inside of the two elements that we care about. If so, we will set the appropriate instance variable and reset the currentElement instance variable.

In this case, we are not going to use the didEndElement in this case so keep this method empty.

Implement the parserDidEndDocument method. Here we are going to add the logic to determine if the email is valid, invalid, or a trap. Then we will display the results in the label that is currently blank.

Finally, we are going add the code to instantiate the parser, load it with the XML that was returned from the API call, set the delegate, and start it. Go back up to the blank connectionDidFinishLoading method and add the following code.


Calling a Web API from iOS is extremely simple. It is a matter of simply calling the API and parsing the results. Web APIs are an extremely easy way to incorporate live data from the Internet into your iPhone and iPad applications. You can download the full source code for this project here.

Are you creating APIs for your organization? What buying criteria should you use when evaluating API management vendors? Download this guide for what you should know before beginning your search for an API management solution. 

Get the API Management Buyers' Guide


Interested in Android? We also have a Android version of this tutorial here.

Subscribe by Email

More Info