Using RestKit with Swift

By Akila Balasubramanian

What is RestKit?

RestKit is an Objective-C framework that simplifies interaction with RESTful web services. It combines a clean, simple HTTP request/response API with a powerful object mapping system that reduces the amount of code you need to write to ‘get stuff done’. RestKit does a lot of the heavy-lifting (integrated network operations, JSON/XML parsing, object-mapping, etc.) for you while allowing you to think more in terms of your application’s data model and worry less about the details of sending requests, parsing responses, and building representations of remote resources. Additionally, it has a powerful wrapper for Core Data.

At the time of this article, it is still an Objective-C framework that requires additional configuration to be used in a Swift project.

This article explains with an example, how RestKit could be used in a Swift project to make a REST call and map the response to a desired model type. To accomplish this, we will be using an Objective-C bridging header file that exposes the required headers to Swift.

This example uses Xcode 7.3.1 and Swift 2.2.

Set up a Swift project via Xcode

Step 1: Create a Single View Application project in Xcode.

Step 2: Remember to choose Swift for your Language preferences.

Install RestKit

The recommended way to install RestKit is via the CocoaPods package manager as it provides flexible dependency management.

Step 1: Install CocoaPods (if not already available).

NOTE: CocoaPods is built with Ruby and it will be installable with the default Ruby available on macOS. If you encounter problems during installation, please visit this guide: https://guides.cocoapods.org/using/troubleshooting#installing-cocoapods

This example uses cocoapods 1.0.1 and ruby 2.3.1.

Step 2: Go to the directory of your Xcode project and create a Podfile.

Step 3: Edit your Podfile to include RestKit.

Step 4: Install RestKit into your project.

Step 5: Open your project in Xcode using the .xcworkspace file.

Create an Objective-C bridging header

Xcode will automatically configure an Objective-C bridging header, if you create an Objective-C file in a Swift project.

Step 1: Create an Objective-C file inside your project folder by right-clicking on the folder and selecting “New File…”.

Step 2: In the dialog that shows up, select Objective-C file under iOS -> Source category. Click Next, provide a name for the file and complete the file creation process.

Step 3: Xcode will automatically offer to create a bridging header file. If you accept, Xcode creates the file and names it as “<Project-module>-Bridging-Header.h”.

Step 4: (Optional) You may now delete the dummy Objective-C file created in Step 1 of this section.

Import RestKit

Step 1: Open the bridging header file and import RestKit.

Step 2: Build your project and make sure there are no errors.

Congratulations! You have now integrated RestKit in your Swift project.

Fetch a REST Resource

We are now going to make a simple GET request to JSONPlaceholder (https://jsonplaceholder.typicode.com) using RestKit. JSONPlaceholder has a “posts” API that returns a collection of posts. The structure of the “post” JSON returned is shown below:

Create a model class

Create a Swift file and name it Post.swift. This file contains the model class which holds the data from the REST API. We would use RestKit’s object mapping capabilities to transform the above JSON into a Post instance.

Define Object Mappings

NOTE: The purpose of this article is to demonstrate the use of RestKit in a Swift project. To keep things simple, the networking code has been placed inside the ViewController. Ideally, we would have a thin controller and create a separate networking layer that handles REST requests.

Henceforth, we will be placing all of the code below in the viewDidLoad() method inside ViewController.swift.

Let’s define our object mappings first:

RKObjectMapping is used to define the rules for transforming data within the parsed payload to attributes on an instance of Post. If the attributes do not precisely match the field names in the payload, addAttributeMappingsFromDictionary() may be used to define the appropriate mappings.

Create a Response Descriptor

The response descriptor verifies that an HTTP response (encountered in the HTTP success code range) matches the object mapping defined above. It also establishes the path pattern.

Initialize an Object Manager

The object manager gets initialized with a new AFHTTPClient which in turn is initialized with the given base URL.

GET Objects at Path

The object manager is used to perform a GET request with a URL for the given path. This creates an RKObjectRequestOperation object that manages the transmission of the HTTP request, deserialization of the response and parsing of the response through the object mapping engine.

Note that the mappingResult needs to be type casted to our model type.

Conclusion

In this article, we learned how to configure a Swift project to use RestKit. We also used RestKit to fetch data from remote APIs and map the parsed payload to a model using object mappings.

Here is the example project with all of the code explained above.

Financial Engines TechBlog

Technological insights in the FinTech space

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store