Moving to promises on iOS

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.

Code & Wild

Thoughts on technology and culture at Bloom&Wild, the UK's most loved flower gifting company. See more at https://github.com/BloomAndWild

Catalina-Ionela Popa-Cornet

Written by

Code & Wild

Thoughts on technology and culture at Bloom&Wild, the UK's most loved flower gifting company. See more at https://github.com/BloomAndWild

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade