Oleg's software

Saving a JSON array of records from iOS Swift 3 application using Loopback 3.

I have a side project for iOS which accepts user input as well as displays some data from third party source. For that I am building a smart backend which will store user records, fetch and store data from remote server and ready to deliver it to a consumer on demand. So for the backend I use Loopback 3 + RethinkDb stack which provides CRUD from out of the box and can be easily expanded with application logic. And I want to save an array of user records from iOS Swift 3 application in RethinkDb using Loopback.

Swift 3

loopback-ios-sdk – failed

First attempt was to implement official Strongloop SDK for iOS which is written in Objective-C but available in Swift through bridging. Unfortunately with Swift 3 this SDK is no longer working as stated in the issue in github.

Loopback

Loopback provides a feature to save a bunch of user records with just one POST – you just need to send a JSON array of records in HTTP body, just like that:

This BDD shows that client should submit POST request with an JSON array of objects in order for Loopback to save it in RethinkDB automatically, without any custom logic.

Alamofire

As we can see saving data in Loopback is easy and can be developed on top of any library that can send JSON array in http body using POST method. Alamofire is convenient and well known solution for that. As of time of writing this article there is Alamofire 4.0.0 for Swift 3 which is amazing. API for sending a request in stright-forward:

Sorry for the copy paste from Alamofire docs. You may notice here that the request is dictionary. Changing it to Array will cause an error in xcode.

Backend.swift:17:31: Contextual type 'Parameters' (aka 'Dictionary<String, Any>') cannot be used with array literal

This means parameters can only be a map of keyed values.

Small tweak can help us. We are going to create a new rule how to encode http body in a request for Alamofire. In order for that let’s extend String class with the following code.

So now it conforms with ParameterEncoding protocol and provides an encode method which will setup request assigning http body and content type. Http body value will be simply copied from a String itself and content type will be set to json as we are using this format to communicate with Loopback. As simple as that.

In the iOS app we will add a request itself:

Now we are ready to run the app and see the results!

This is an express-bunyan-logger output of the Loopback app. We can see that the body is an array of objects and short-body is cutted off (not sure whether it is normal). And in RethinkDb Data Explorer we will be able to see them. RethinkDB documents after Loopback POST

Conclusion

Loopback is a great framework to build APIs quickly, but it’s iOS support is limited. Fortunately there are powerful tools written in Swift 3 which is highly customizable and provide a great deal for integration task.