iOS App Development

How to make an app talk to database using RestKit

Most of the successful apps that are created today will most certainly talk to a remote database of some sort. There are different ways by which the data present in these databases are exposed to outside world.

  • ) REST API
  • ) Client Libraries ( Which makes it really easy to talk to a remote database by hiding most of the low level networking code).

When it comes to iOS backend many people go with Parse which is a pretty popular backend as a service. They provide libraries for iOS, Android and javascript api’s.

In this post we will use MongoLab which provide REST api to mongodb database and RestKit which is a object mapper to retrieve data from mongodb and convert to swift objects.

This is the app for which we are building the backend.

Create Mongolab account

  • ) Go to Mongolab and create an account
  • ) Create a new database called iosdb
  • ) Create a new collection iosnews and document like below
{
    "news":"iOS 8 CloudKit tutorial",
    "url" :"https://shrikar.com/blog/2014/10/12/ios8-cloudkit-tutorial-part-1/"
}

In the documentation we can find out how to get the list of all documents in the collection https://api.mongolab.com/api/1/databases/iosdb/collections/iosnews?apiKey=myAPIKey

 

RestKit Mapping.

Lets create a FlashCard class which maps the mongodb document into objects.

//
//  FlashCard.swift
//  FlashCard
//
//  Created by Shrikar Archak on 12/1/14.
//  Copyright (c) 2014 Shrikar Archak. All rights reserved.
//

import UIKit

class FlashCard: NSObject {
    var news: String = ""
    var url : String = ""
}

RKObjectMapping

An RKObjectMapping object describes a transformation between object representations using key-value coding and run-time type introspection. The mapping is defined in terms of a source object class and a collection of RKPropertyMapping objects describing how key paths in the source representation should be transformed into attributes and relationships on the target object.

Find more documentation here RestKit

In our case it will be mapping url and news key paths.

let mapDict = ["news":"news","url":"url"]
let flashCardMapping = RKObjectMapping(forClass: FlashCard.self)
flashCardMapping.addAttributeMappingsFromDictionary(mapDict)

RKResponseDescriptor

Describes an object mappable response that may be returned from a remote web application in terms of an object mapping, a key path, a SOCKit pattern for matching the URL, and a set of status codes that define the circumstances in which the mapping is appropriate for a given response.

let responseDescriptor = RKResponseDescriptor(mapping: flashCardMapping,
method: RKRequestMethod.GET,
pathPattern: "/api/1/databases/iosdb/collections/iosnews/",
keyPath: nil,
statusCodes: NSIndexSet(index: 200))
objectManager?.addResponseDescriptor(responseDescriptor)

getObjectsAtPath

The next step once we have the objectManager configured is to get the objects like below

objectManager?.getObjectsAtPath("/api/1/databases/iosdb/collections/iosnews/", parameters: ["apiKey" : "yourkey","s":"{\"_id\":-1}"], success: { (operation, result) -> Void in
       let data : [FlashCard] = result!.array() as [FlashCard]
      /* Here the data is the rest response mapped as an array of FlashCard objects */
       self.flashCards = data
       }, failure: { (operation, error) -> Void in
           NSLog("\(error)")
   })

About the author

Shrikar

Backend/Infrastructure Engineer by Day. iOS Developer for the rest of the time.

/* ]]> */