Bolts – BFTaskCompletionSource, a promise factory

In this lesson

  • BFTaskCompletionSource is a Bolts class that is useful in certain scenarios to create BFTasks (Promises)

Transcript

Tap on time to skip ahead

00:11

BFTaskCompletionSource is another of the three main classes in the Bolts framework that you need to become familiar with. It is essentially a factory for creating promises. To take a look at where I use that in the application, there’s a couple places but probably the easiest to understand is inside the dataDragon module.

00:33

Inside task, there’s a method or a command called get champion static data task. This is a command that runs asynchronously using AFNetworking, the standard, de facto library for doing networking in iOS apps. To hit a URL here, this is part of the URL. It hits the Riot Games dataDragon champion URL to retrieve a list of champions that have been released for the current version of the game.

01:12

I use the completion source here to- I just create an instance, then I use the AFNetworking API to retrieve, or to hit that API and get data back. It uses a different mechanism for handling asynchronous requests. I have to pass along a success handler here and a failure handler here.

01:40

What I do is, this code runs asynchronously. I create a factory here and then I schedule this work to be done on another background queue managed by AFNetworking. I simply return the promise right here. This runs later, but the requester gets a promise back immediately. This simply is a- I keep a reference to this because I use it later when I do finally get a successful result back from AFdNetworking. I simply set the result on the promise,which is again the completion source, and I- whatever came back from AF Networking on this URL request here, gets set as the result. This causes the promise to resolve to whoever called this. Its continuation block will fire.

02:46

If I get a failure instead, if I get some error, a networking error. Let’s say if I was in airport mode something or the API was down, I would get an error. I would resolve the same promise with the error that came back. Regardless, this promise got returned immediately to its caller. I kept a reference to the task completion source and I used it here in this asynchronous callback to resolve the promise.

03:17

It’s kind of a unique use case, but you may find yourself using the promise factory, BFTask completion source, and studying this code and the other uses in the application with help familiarize yourself with it.