Multitasking Support on the ios Platform Priya Rajagopal Invicara (www.invicara.com) @rajagp
Multitasking on ios? Multitasking allows apps to perform certain tasks in the background while you're using other apps or not using your device * * Source: apple.com 2
Long long ago.
Pre ios7 Finite time to wrap up what you are doing self.bgtaskid = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler ({ () -> Void in UIApplication.sharedApplication().endBackgroundTask(self.bgTaskId) self.bgtaskid = UIBackgroundTaskInvalid }) self.domytaskthatshouldcompleteinbackground() Long Running Background Operations VoIP, Audio, Location, BT LE Background Operations performed in context of running App 4
Wasn t Enough I want my users to be greeted with up-to-date status info every time they launch my social networking app I want the latest episode of my favorite podcast to be downloaded automatically when its available. I want the docs that I added/edited in my document sharing app to be pushed out to my cloud share but I am not going to wait around for the upload to complete.and I want all of this without draining my battery or blowing through my data plan 5
Welcome to the new world
ios7 + Background Fetches Background Notifications Background Transfers Any app can run in the background Be a good citizen 7
Background Fetches
Background Fetches System wakes up app periodically using an Opportunistic / Discretionary algorithm App launched/resumed Finite time to perform task when woken up Must inform system when finished with task 9
Background Fetches UIApplicationBackgroundFetchIntervalMinimum Or custom time intervals MinInterval MinInterval MinInterval 10
Enabling Background Fetch Set Capabilities 11
Enabling Background Fetch Set minimum fetch time interval in AppDelegate func application(application: UIApplication, didfinishlaunchingwithoptions launchoptions: [NSObject: AnyObject]?) -> Bool { UIApplication.sharedApplication().setMinimumBackgroundFetchInterval( UIApplicationBackgroundFetchIntervalMinimum) return true } 12
Enabling Background Fetch Handle AppDelegate callback - Record Completion Handler func application(application: UIApplication, performfetchwithcompletionhandler completionhandler: (UIBackgroundFetchResult) -> Void) { // Record completion handler } Callback w/ status when done with background fetch NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in if context!.bgfetchtaskcompletionhandler!= nil { context!.bgfetchtaskcompletionhandler!(uibackgroundfetchresult.newdata) } }) 13
Demo
Background Notifications
Silent Notifications Apple Push Notification Service Notification Web Service (Provider) Notification Request Data Response Data App Mobile Device 16
Background Notifications Specially crafted Remote Notifications messages Silent App launched/ resumed in background Finite time to perform task when woken up Must inform system when finished with task APN Servers rate limits notifications Many API changes in ios8 17
Background Notifications Specially crafted message { } "aps" : { sound :, content-available :1 } 18
Enabling Background Notifications Set Capabilities 19
Enabling Background Notifications Register for remote notifications UIApplication.sharedApplication().registerForRemoteNotifications() Listen for registration callback for device token func application(application: UIApplication, didregisterforremotenotificationswithdevicetoken devicetoken: NSData) { // Register the device token with your web server (provider) } Users automatically opted in for BG notifications Check changes to User Preferences func isregisteredforremotenotifications() - > Bool 20
Enabling Background Notifications func application(application: UIApplication, didreceiveremotenotification userinfo: [NSObject : AnyObject], fetchcompletionhandler completionhandler: (UIBackgroundFetchResult) -> Void) { if!(uiapplication.sharedapplication().isregisteredforremotenotifications()){ completionhandler (UIBackgroundFetchResult.NoData) } else { // Handle notifications } } Callback w/ status when done NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in if context!.bgfetchtaskcompletionhandler!= nil { context!.bgfetchtaskcompletionhandler!(uibackgroundfetchresult.newdata) } }) 21
Recap Set Capability Implement AppDelegate callback Callback System w/ Completion Handler when finished with task 22
Background Transfers
Out-of-Process Transfers App Background Daemon Create Background Session w/ Task(s) Perform Task(s) Handle Background Events w/ Completion Handler Reassociate w/ BG Session Delegate Callbacks All tasks Completed Completion Handler 24
Background Transfers Uses NSURLSessions Out-Of-Process Data Transfers regardless of App State HTTP(s) Only Downloads/ Uploads Transfers Initiated in Foreground or in Background App called back to handle events for a BG Session App must inform system on completion of all tasks in BG Session 25
Background Transfers Every Background Session has UNIQUE identifier Discretionary Mode Swipe To Delete in App Switcher will stop background tasks Use in conjunction w/ Background Fetches or Silent Notifications 26
Background Transfers Create (/Copy) Session Configuration Object var bgsessionconfig:nsurlsessionconfiguration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(sessionIdentifier) Create Background Session w/ Configuration Object var downloadsession:nsurlsession = NSURLSession(configuration: bgsessionconfig, delegate: self, delegatequeue: nil) Create appropriate Download/Upload Task to be performed in BG var downloadtask:nsurlsessiondownloadtask = downloadsession.downloadtaskwithrequest(request) And Don t Forget. Resume Task downloadtask.resume() 27
Background Transfers Listen to events on App Delegate callback func application(application: UIApplication, handleeventsforbackgroundurlsession identifier: String, completionhandler: () -> Void) Re-associate with the background session if required Callback using handler when done with tasks 28
Demo
Security Implications Keychain Access Attributes (ksecattraccessible) ksecattraccessibleafterfirstunlock ksecattraccessibleafterfirstunlockthisdeviceonly File Protection Attributes (NSFileProtectionKey) NSFileProtectionCompleteUnlessOpen NSFileProtectionCompleteUntilFirstUserAuthentication NSData (NSDataWritingOptions) NSDataWritingFileProtectionCompleteUnlessOpen NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication Core Data (NSPersistentStoreFileProtectionKey) NSFileProtectionCompleteUntilFirstUserAuthentication (default) 30
ios8 Extensions Document Provider Uploads and Downloads in the background session 31
Summary Powerful Multitasking Capabilities Background Fetches Background/Silent Notifications Background Transfers Smart Discretionary Algorithm You get only few seconds so use Background Transfers Don t forget to inform the system when you are done 32
More Information WWDC 2013 - What s new in Foundation Networking WWDC 2013 - What s new in multitasking WWDC 2014 - What s new in Foundation Networking WWDC 2014 - What's New in ios Notifications, Session 713 33
Thank You! Priya Rajagopal @rajagp 34