Skip to content

Download Status Example

Andy Johns edited this page Feb 19, 2016 · 1 revision

Predix Mobile iOS Snippet -- Show download status detail

In the example Predix Mobile iOS container app, the waiting spinner is implemented as just a simple spinner. But what if you want to display more information? For example, how about the number of documents downloaded and remaining to download while the system is syncing your local database at startup?

It's easy!

While there are several ways to show this information, here's a quick example to get you started:

If you're using the PredixMobileReferenceApp, All this code is added to the ViewController.swift class.

There's a notifcation posted, "DatabaseDownloadNotification" when the system is syncing data. The technique involves, when the updateWaitState is called when the message is the "downloading data" message, then listen for this notification. The notification's object contains the information needed to display the status of the download. Don't forget to stop listening and clean up your notification observer when no longer waiting!

First add a property to the ViewController:

private var replicationUpdateObserver : NSObjectProtocol?

Then add a few lines to the updateWaitState(state: WaitState, message: String?) function:

When the state is .Waiting:

    if message == Messages.DownloadingData.description
    {
        self.watchReplicationUpdates()
    }

And when the state is .NotWaiting:

    if let replicationUpdateObserver = self.replicationUpdateObserver
    {
        self.replicationUpdateObserver = nil
        NSNotificationCenter.defaultCenter().removeObserver(replicationUpdateObserver)
    }

Finally, add the watchReplicationUpdates() referenced in the .Waiting state:

func watchReplicationUpdates()
{
    // Create an observer for the "DatabaseDownloadNotification" notification
    self.replicationUpdateObserver = NSNotificationCenter.defaultCenter().addObserverForName(DatabaseDownloadNotification, object: nil, queue: nil, usingBlock: { (notification: NSNotification) -> Void in

        // if the object is a dictionary that contains a "completedChangesCount" and a "totalChangesCount"
        if let dataDic = notification.object as? [String: AnyObject], completedChangesCount = dataDic["completedChangesCount"], totalChangesCount = dataDic["totalChangesCount"]
        {
            // Update the UI message in the main queue
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.spinnerLabel.text = Messages.DownloadingData.description.stringByAppendingString(" \(completedChangesCount) of \(totalChangesCount)")
            })
        }
        
    })
}

Obviously this techinque could be used with a variety of UI treatments; progress bars, custom spinners, more detailed messages, etc. Now that you see how it works, try it yourself!