Moving to promises on iOS

Catalina-Ionela Popa-Cornet
Code & Wild
Published in
3 min readNov 6, 2019

Hi I’m Catalina, one of the iOS developers at Bloom & Wild. Today I wanted to share our journey of moving to promises, explaining why we did it and some of the challenges we encountered along the way.

Our problem

Most of our API calls are made in a singleton, which uses a callback closure that will be called when the task is completed (by sending the result or the error). Although this might seem easy, our problem was that most of the API calls were dependent on other API call results, making the code harder to maintain and difficult to follow.

Solution

The solution which most fitted our needs was promises. We wanted to remove duplication from our codebase so we created a class to both encapsulate a pending promise and a resolver.

One of the challenges we came across was consistency and because consistency is key in every codebase, we made resolving promises bulletproof by conforming the APIPromise to a response protocol. Using generics we made sure that the return type of the promise will be our defined models.

In this class we get the API request and use data to make a basic call using URLSessionDataTask. By following this implementation we only have one completion handler where the promise is getting resolved after parsing the response received.

We mapped key methods from the promise framework, such as ‘done’, ‘then’ & ‘catch’ into our own promise, so that we could return the correct type upon the promise being resolved.

Here is an example of promises being used within our codebase.

Conclusion

Promises are the best way for us to transform completion blocks into a chained asynchronous process that is easy to understand and maintain by the team, but also to enforce type safety by using generics.

--

--