Consuming a WebApi Asynchronously in Xamarin iOS

Introduction

There are a seemingly endless variety of web services available, like: Amazon, Facebook, and Twitter just to name a few. For developers, being able to access those services allows them opportunities to either extend the capabilities of their own applications by integrating with these services or building new applications using the APIs provided to them over the web.

One great example is the StackExchange family of question and answer sites. StackExchange exposes a rich set of APIs that allow application developers to access almost any data they could imagine from Stack Exchange.

In this article I am going to be using the StackExchange API to access featured questions from the StackOverflow site and display them in an iOS TableView.

**Note: The source code for this article is hosted on GitHub in the TableDemo project, Part2 folder and builds on my previous article ‘A better UITableViewSource in Xamarin iOS’.

Getting Started

First, we need to create a model class to represent the question data that returns from StackExchange. For this example we’re only interested in the question’s title even though there are many more properties in the question object. Here is Question.cs:

public class Question
{
  // title property exposed via the StackExchange webapi
  public string title { get; set; }

  // Override the ToString method to specify what displaying in the
  // TableView's TextLabel Text
  public override string ToString()
  {
    return title;
  }
}

Importing the RestSharp Component

Before we can access the data from the WebApi we need to include a 3rd part component to handle making the Rest Requests to the api. I like to use the RestSharp library which is available through the component library in Xamarin Studio. RestSharp is a simple WebApi client for .NET that makes consuming web services easy. While, you most certainly could write the code to handle the communication with the web services on your own, I find that RestSharp is reliable, easy to use, and provides all of the features I need like object serialization/deserialization and authentication. The RestSharp website has information about how to get questions answered, samples, and links to the project’s source code.

To add this component to our project all we need to do is to right-click on the Components folder in our project and select the ‘Get more components…’ menu option.

Get more components

In the component library when we search for RestSharp we are able to include the library from the search results.

Screen Shot 2013-09-09 at 11.09.07 PM

Loading WebApi Data Asynchronously

Now that we have RestSharp included, we need to add a method to load the data for the TableView to HomeScreen.cs. Here we use the RestSharp library to load the data asynchronously from the StackExchange API. Loading the data asynchronously is an extremely important consideration in application design. It keeps the user interface responsive while the data load is happening and allows for the background handling of any errors that may occur, like there being no network connection or some other data processing exception.

void LoadData()
{
  var request = new RestRequest {RootElement = "items", Resource = "/questions/featured"};
  request.AddParameter("site", "stackoverflow");

  var client = new RestClient("http://api.stackexchange.com/2.1");
  client.ExecuteAsync<List<Question>> (request, response => {
    // do work on UI thread
    InvokeOnMainThread(delegate {
      // pass the data to the TableSource class
      ((TableSource<Question>)table.Source).Data = response.Data;

      // make the TableView reload the data
      table.ReloadData();
    });
  });
}

To complete our update, all we need to do is update the ViewDidLoad method to initialize our modified TableSource and to call the LoadData method.

public override void ViewDidLoad ()
{
  base.ViewDidLoad ();
  table = new UITableView(View.Bounds);
  table.AutoresizingMask = UIViewAutoresizing.All;

  // new TableSource to handle Question model
  var tableSource = new TableSource<Question>();

  // display the question's title when a row is selected
  tableSource.OnRowSelected += (object sender, TableSource<Question>.RowSelectedEventArgs e) => {
    new UIAlertView("Row Selected", 
      tableSource.Data[e.indexPath.Row].ToString(), null, "OK", null).Show();
    e.tableView.DeselectRow (e.indexPath, true);
  };
  table.Source = tableSource;
  Add (table);

  // Load data from the WebApi using RestSharp
  LoadData();
}

Finally

Now when we run our application it looks like this:

iOS Simulator Screen shot Sep 9, 2013 11.22.46 PM

We’ve built a basic iOS TableView application that asynchronously accesses WebApi data from the StackExchange api. We loaded the data asynchronously keeping the application responsive, even during slow data loads.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s