Stay foolish,stay hungry

Bolts Introduction

Sep6th, 20158:35 am

Bolts

Bolts is a collection of low-level libraries designed to make developing mobile
apps easier. Bolts was designed by Parse and Facebook for our own internal use,
and we have decided to open source these libraries to make them available to
others. Using these libraries does not require using any Parse services. Nor
do they require having a Parse or Facebook developer account.

Bolts includes:

“Tasks”, which make organization of complex asynchronous code more manageable. A task is kind of like a JavaScript Promise, but available for iOS and Android.

An implementation of the App Links protocol, helping you link to content in other apps and handle incoming deep-links.

Tasks

To build a truly responsive iOS application, you must keep long-running operations off of the UI thread, and be careful to avoid blocking anything the UI thread might be waiting on. This means you will need to execute various operations in the background. To make this easier, we’ve added a class called BFTask. A task represents the result of an asynchronous operation. Typically, a BFTask is returned from an asynchronous function and gives the ability to continue processing the result of the task. When a task is returned from a function, it’s already begun doing its job. A task is not tied to a particular threading model: it represents the work being done, not where it is executing. Tasks have many advantages over other methods of asynchronous programming, such as callbacks. BFTask is not a replacement for NSOperation or GCD. In fact, they play well together. But tasks do fill in some gaps that those technologies don’t address.
* BFTask tasks care of managing dependencies for you. Unlike using NSOperation for dependency management, you don’t have to declare all dependencies before starting a BFTask. For example, imagine you need to save a set of objects and each one may or may not require saving child objects. With an NSOperation, you would normally have to create operations for each of the child saves ahead of time. But you don’t always know before you start the work whether that’s going to be necessary. That can make managing dependencies with NSOperation very painful. Even in the best case, you have to create your dependencies before the operations that depend on them, which results in code that appears in a different order than it executes. With BFTask, you can decide during your operation’s work whether there will be subtasks and return the other task in just those cases.
* BFTasks release their dependencies. NSOperation strongly retains its dependencies, so if you have a queue of ordered operations and sequence them using dependencies, you have a leak, because every operation gets retained forever. BFTasks release their callbacks as soon as they are run, so everything cleans up after itself. This can reduce memory use, and simplify memory management.
* BFTasks keep track of the state of finished tasks: It tracks whether there was a returned value, the task was cancelled, or if an error occurred. It also has convenience methods for propagating errors. With NSOperation, you have to build all of this stuff yourself.
* BFTasks don’t depend on any particular threading model. So it’s easy to have some tasks perform their work with an operation queue, while others perform work using blocks with GCD. These tasks can depend on each other seamlessly.
* Performing several tasks in a row will not create nested “pyramid” code as you would get when using only callbacks.
* BFTasks are fully composable, allowing you to perform branching, parallelism, and complex error handling, without the spaghetti code of having many named callbacks.
* You can arrange task-based code in the order that it executes, rather than having to split your logic across scattered callback functions.

For the examples in this doc, assume there are async versions of some common Parse methods, called saveAsync: and findAsync: which return a Task. In a later section, we’ll show how to define these functions yourself.

The continueWithBlock Method

Every BFTask has a method named continueWithBlock: which takes a continuation block. A continuation is a block that will be executed when the task is complete. You can then inspect the task to check if it was successful and to get its result.

In many cases, you only want to do more work if the previous task was successful, and propagate any errors or cancellations to be dealt with later. To do this, use the continueWithSuccessBlock: method instead of continueWithBlock:.

Chaining Tasks Together

BFTasks are a little bit magical, in that they let you chain them without nesting. If you return a BFTask from continueWithBlock:, then the task returned by continueWithBlock: will not be considered finished until the new task returned from the new continuation block. This lets you perform multiple actions without incurring the pyramid code you would get with callbacks. Likewise, you can return a BFTask from continueWithSuccessBlock:. So, return a BFTask to do more asynchronous work.

Error Handling

By carefully choosing whether to call continueWithBlock: or continueWithSuccessBlock:, you can control how errors are propagated in your application. Using continueWithBlock: lets you handle errors by transforming them or dealing with them. You can think of failed tasks kind of like throwing an exception. In fact, if you throw an exception inside a continuation, the resulting task will be faulted with that exception.

It’s often convenient to have a long chain of success callbacks with only one error handler at the end.

Creating Tasks

When you’re getting started, you can just use the tasks returned from methods like findAsync: or saveAsync:. However, for more advanced scenarios, you may want to make your own tasks. To do that, you create a BFTaskCompletionSource. This object will let you create a new BFTask, and control whether it gets marked as finished or cancelled. After you create a BFTask, you’ll need to call setResult:, setError:, or cancel to trigger its continuations.

Tasks in Parallel

You can also perform several tasks in parallel, using the taskForCompletionOfAllTasks: method. You can start multiple operations at once, and use taskForCompletionOfAllTasks: to create a new task that will be marked as completed when all of its input tasks are completed. The new task will be successful only if all of the passed-in tasks succeed. Performing operations in parallel will be faster than doing them serially, but may consume more system resources and bandwidth.

// Objective-C
PFQuery *query = [PFQuery queryWithClassName:@"Comments"];
[query whereKey:@"post" equalTo:@123];
[[[self findAsync:query] continueWithBlock:^id(BFTask *results) {
// Collect one task for each delete into an array.
NSMutableArray *tasks = [NSMutableArray array];
for (PFObject *result in results) {
// Start this delete immediately and add its task to the list.
[tasks addObject:[self deleteAsync:result]];
}
// Return a new task that will be marked as completed when all of the deletes are
// finished.
return [BFTask taskForCompletionOfAllTasks:tasks];
}] continueWithBlock:^id(BFTask *task) {
// Every comment was deleted.
return nil;
}];
// Swift
var query = PFQuery(className:"Comments")
query.whereKey("post", equalTo:123)
findAsync(query).continueWithBlock {
(task: BFTask!) -> BFTask in
// Collect one task for each delete into an array.
var tasks = NSMutableArray.array()
var results = task.result() as NSArray
for result : PFObject! in results {
// Start this delete immediately and add its task to the list.
tasks.addObject(self.deleteAsync(result))
}
// Return a new task that will be marked as completed when all of the deletes
// are finished.
return BFTask(forCompletionOfAllTasks:tasks)
}.continueWithBlock {
(task: BFTask!) -> AnyObject! in
// Every comment was deleted.
return nil
}

Task Executors

Both continueWithBlock: and continueWithSuccessBlock: methods have another form that takes an instance of BFExecutor. These are continueWithExecutor:withBlock: and continueWithExecutor:withSuccessBlock:. These methods allow you to control how the continuation is executed. The default executor will dispatch to GCD, but you can provide your own executor to schedule work onto a different thread. For example, if you want to continue with work on the UI thread:

// Create a BFExecutor that uses the main thread.
BFExecutor *myExecutor = [BFExecutor executorWithBlock:^void(void(^block)()) {
dispatch_async(dispatch_get_main_queue(), block);
}];
// And use the Main Thread Executor like this. The executor applies only to the new
// continuation being passed into continueWithBlock.
[[self fetchAsync:object] continueWithExecutor:myExecutor withBlock:^id(BFTask *task) {
myTextView.text = [object objectForKey:@"name"];
}];

For common cases, such as dispatching on the main thread, we have provided default implementations of BFExecutor. These include defaultExecutor, immediateExecutor, mainThreadExecutor, executorWithDispatchQueue:, and executorWithOperationQueue:. For example:

Task Cancellation

It’s generally bad design to keep track of the BFTaskCompletionSource for cancellation. A better model is to create a “cancellation token” at the top level, and pass that to each async function that you want to be part of the same “cancelable operation”. Then, in your continuation blocks, you can check whether the cancellation token has been cancelled and bail out early by returning a [BFTask cancelledTask]. For example:

Note: The cancellation token implementation should be thread-safe.
We are likely to add some concept like this to Bolts at some point in the future.

App Links

App Links provide a cross-platform mechanism that allows a developer to define and publish a deep-linking scheme for their content, allowing other apps to link directly to an experience optimized for the device they are running on. Whether you are building an app that receives incoming links or one that may link out to other apps' content, Bolts provides tools to simplify implementation of the App Links protocol.

Handling an App Link

The most common case will be making your app receive App Links. In-linking will allow your users to quickly access the richest, most native-feeling presentation of linked content on their devices. Bolts makes it easy to handle an inbound App Link (as well as general inbound deep-links) by providing utilities for processing an incoming URL.

For example, you can use the BFURL utility class to parse an incoming URL in your AppDelegate:

Navigating to a URL

Following an App Link allows your app to provide the best user experience (as defined by the receiving app) when a user navigates to a link. Bolts makes this process simple, automating the steps required to follow a link:

Resolve the App Link by getting the App Link metadata from the HTML at the URL specified.

Step through App Link targets relevant to the device being used, checking whether the app that can handle the target is present on the device.

If an app is present, build a URL with the appropriate al_applink_data specified and navigate to that URL.

Otherwise, open the browser with the original URL specified.

In the simplest case, it takes just one line of code to navigate to a URL that may have an App Link:

[BFAppLinkNavigation navigateToURLInBackground:url];

Adding App and Navigation Data

Under most circumstances, the data that will need to be passed along to an app during a navigation will be contained in the URL itself, so that whether or not the app is actually installed on the device, users are taken to the correct content. Occasionally, however, apps will want to pass along data that is relevant for app-to-app navigation, or will want to augment the App Link protocol with information that might be used by the app to adjust how the app should behave (e.g. showing a link back to the referring app).

If you want to take advantage of these features, you can break apart the navigation process. First, you must have an App Link to which you wish to navigate:

Resolving App Link Metadata

Bolts allows for custom App Link resolution, which may be used as a performance optimization (e.g. caching the metadata) or as a mechanism to allow developers to use a centralized index for obtaining App Link metadata. A custom App Link resolver just needs to be able to take a URL and return a BFAppLink containing the ordered list of BFAppLinkTargets that are applicable for this device. Bolts provides one of these out of the box that performs this resolution on the device using a hidden UIWebView.

You can use any resolver that implements the BFAppLinkResolving protocol by using one of the overloads on BFAppLinkNavigation:

App Link Return-to-Referer View

When an application is opened via an App Link, a banner allowing the user to “Touch to return to ” should be displayed. The BFAppLinkReturnToRefererView provides this functionality. It will take an incoming App Link and parse the referer information to display the appropriate calling app name.

- (void)viewDidLoad {
[super viewDidLoad];
// Perform other view initialization.
self.returnToRefererController = [[BFAppLinkReturnToRefererController alloc] init];
// self.returnToRefererView is a BFAppLinkReturnToRefererView.
// You may initialize the view either by loading it from a NIB or programmatically.
self.returnToRefererController.view = self.returnToRefererView;
// If you have a UINavigationController in the view, then the bar must be shown above it.
[self.returnToRefererController]
}

The following code assumes that the view controller has an openedAppLinkURLNSURL property that has already been populated with the URL used to open the app. You can then do something like this to show the view:

- (void)viewWillAppear {
[super viewWillAppear];
// Show only if you have a back AppLink.
[self.returnToRefererController showViewForRefererURL:self.openedAppLinkURL];
}

In a navigaton-controller view hierarchy, the banner should be displayed above the navigation bar, and BFAppLinkReturnToRefererController provides an initForDisplayAboveNavController method to assist with this.

Analytics

Bolts introduces Measurement Event. App Links posts three different Measurement Event notifications to the application, which can be caught and integrated with existing analytics components in your application.

al_nav_out — Raised when your app switches out to an App Links URL.

al_nav_in — Raised when your app opens an incoming App Links URL.

al_ref_back_out — Raised when your app returns back the referrer app using the built-in top navigation back bar view.

Listen for App Links Measurement Events

There are other analytics tools that are integrated with Bolts' App Links events, but you can also listen for these events yourself: