Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

iOS4 multitasking development notes


Published on

iOS4/SDK4.0 multitasking support from a developer's perspective is my own personal dev.notes I took while writing PlaceTrack, a Latitude background updater (still "in review" since June 18th)

Published in: Technology, News & Politics
  • Nice one
    Are you sure you want to  Yes  No
    Your message goes here

iOS4 multitasking development notes

  1. 1. iPHONE iOS4 / SDK4.0 multitasking support from a developer’s perspective(a dump of my own development notes while writing PlaceTrack) Nico Tranquilli
  2. 2. iPHONE MULTITASKING quitting (pressing Home) a running application on iOS 4.0 causes it to become inactive and be moved to the background. Quitting from the task bar is equivalent to a force quit/termination (kill -9) an application interrupted by a system event (incoming call, SMS, calendar notification) resigns the active state (ie. looses focus). Once the user accepts the interruption, it moves to the background and suspends app.delegate’s methods get called on transitions between foreground and background states (and should be handled appropriately by the developer); other objects can observe appropriate notifications older applications, linked against SDK earlier than 4.0 or running on hw with no multitasking support, always SUSPEND, are KEPT IN RAM (that’s for Fast App Switching) but are NOT going to be USING CPU CYCLESNico Tranquilli • July 2010 “iOS4 multitasking development notes”
  3. 3. MULTITASKING SUPPORT iOS4 on 3G and earlier iPhone models doesn’t support multitasking iOS earlier than 4.0 doesn’t support multitasking any app built against a pre-4.0 SDK still behaves as it did on earlier OS (terminates when you leave and gets the same notifications) when you leave an app built against a 4.0 SDK, it receives applicationDidEnterBackground. On (older) devices with no multitasking support, applicationWillTerminate is called afterwards. developers can explicitly opt out by setting UIApplicationExitsOnSuspend to YES in Info.plistNico Tranquilli • July 2010 “iOS4 multitasking development notes”
  4. 4. APPLICATION’S STATES ‣ executing code in the foreground ACTIVE ‣ receiving events ‣ application has focus still executing code in the foreground but not receiving events applications stay here: INACTIVE ‣ on their way to the background state ‣ when the system is waiting for the user to respond to events ‣ when the user presses the Sleep/Wake button executing code in the background applications stay here: BACKGROUND ‣ on their way to the suspended state (briefly) ‣ if they asked for a (limited) extra processing time ‣ frozen in the background: not executing code but still in memory ‣ push notifications still delivered when the user taps alert’s btn SUSPENDED ‣ events coalesced and delivered later when it resumes ‣ wakes up and moves to the background on registered background events (eg. Significant Location Change)Nico Tranquilli • July 2010 “iOS4 multitasking development notes”
  5. 5. BACKGROUND EXECUTION once in the background, an application can... suspend, shortly after entering this state and be woken up later by events delivered by system background services (Significant Location Change, VoIP) or when user taps a notification’s view button execute your code for a short amount of time, continuing what it was doing before becoming INACTIVE and suspending once the task is complete (or the 600s time limit is reached) keep running in the background for unlimited time, if it was registered for one of the permitted background task (eg. continuos location or background audio)Nico Tranquilli • July 2010 “iOS4 multitasking development notes”
  6. 6. ENTERING BACKGROUND... applicationWillResignActive is called on app.delegate (and UIApplicationWillResignActiveNotification is posted to registered objects) ➡ delivery of touch events is suspended by the system (inactive applications run but do not dispatch incoming events) ➡ you should pause ongoing tasks and wait to transition to either the active or background state ➡ an active application resigns active state... ‣ on incoming phone call/sms or calendar event ‣ when user presses the Sleep/Wake button while running ‣ when user presses the Home button (if background is supported)Nico Tranquilli • July 2010 “iOS4 multitasking development notes”
  7. 7. ENTERING BACKGROUND... applicationDidEnterBackground is called on app.delegate (and UIApplicationDidEnterBackgroundNotification is posted to registered objects) ➡ application is now in the background ➡ system data objects (cache, etc) are automatically released ➡ you should always save user data and state information here (so you can restore it later, just in case it gets terminated) ➡ you should release as much memory as possible to prevent termination ➡ just five seconds to perform any tasks and return (additional time can be requested) before being suspendedNico Tranquilli • July 2010 “iOS4 multitasking development notes”
  8. 8. ACTIVE USER INTERRUPT PRESSES (incoming call, HOME BUTTON sms, event)  save user data  save application state … USER GETS NOTIFIED applicationWillResignActive: INACTIVE  register for bg tasks YES NO  ask for exec. time  schedule local notif. ACCEPT ?  suspend applicationDidEnterBackground: BACKGROUNDNico Tranquilli • July 2010 “iOS4 multitasking development notes”
  9. 9. SAVE DATA BEFORE ENTERING BACKGROUND! apps running in the background still get incoming messages delivered: observe low-memory warnings as usual applicationDidReceiveMemoryWarning: (in your app.delegate’s) didReceiveMemoryWarning (in UIViewController) UIApplicationDidReceiveMemoryWarningNotification when suspended, it won’t get any notice in case of termination: save data and context beforehand! may be purged from memory and terminated during low-memory conditions: always save context and release as much memory as possibile to prevent termination before moving to the background applicationWillTerminate gets called as usual if the application is currently running no termination notice is delivered if the application is suspendedNico Tranquilli • July 2010 “iOS4 multitasking development notes”
  10. 10. BACKGROUND APPLICATIONS SHOULD… postpone any UI updates NEVER make OpenGL ES calls not use system shared resources (contacs db, etc) did I tell you to save state and user data when entering background ?Nico Tranquilli • July 2010 “iOS4 multitasking development notes”
  11. 11. BACKGROUND APPLICATIONS CAN… continue to run, ie. request permission to run in the background and provide an expiration handler (for final cleanup, etc) to be called when your time limit is reached. If your job requires the thread for a long time it makes sense to schedule the work on a dispatch queue so that the run loop is not blocked. respond to registered background events schedule local notifications (sound, alerts, badges) SUSPEND ;-)Nico Tranquilli • July 2010 “iOS4 multitasking development notes”
  12. 12. RUNNING IN THE BACKGROUND background applications have a limited amount of execution time, except for certain (permitted) background tasks you should wrap any long-running (critical) tasks with beginBackgroundTaskWithExpirationHandler: and endBackgroundTask: calls ‣ you can do this while the app is still in foreground ‣ you can start any bg task at quit time (in your didEnterBackground delegate) ‣ you can start any task later when your app is woken up by a registered bg event ‣ limit for task completion is 600secs. Time left to run is in the backgroundTimeRemaining property of UIApplication always provide an expiration handler for each task and call the endBackgroundTask: from there (application gets terminated rather then suspended if you leave outstanding background tasks!)Nico Tranquilli • July 2010 “iOS4 multitasking development notes”
  13. 13. SOME BACKGROUND TYPES ARE DECLARED Support for some types of background execution must be declared in advance including the UIBackgroundModes key in your Info.plist. Possible strings in its array value: audio location – for continuos, high-accuracy, location updates (drains batteries!). Do not use this if all you need are Significant Location Change notifications! voip – VoIp applications are automatically started in the background upon system boot, suspended, woken up by the system on incoming connection (socket handed over)Nico Tranquilli • July 2010 “iOS4 multitasking development notes”
  14. 14. BACKGROUND LOCATION significant location change: suspended application is woken up (or relaunched if not running) on significant location changes. Does NOT need to be declared as a background application. Low-power, recommended standard location updates: location updates are delivered (as usual) to a running fg/bg application. The application gets suspended once background time expires and nothing is delivered when application is suspended or terminated continuous background location: an application registered as a continuos background location app is never suspended by the system and gets continuous location updates in the backgound (turn-by-turn apps and the like). Power-intensive!Nico Tranquilli • July 2010 “iOS4 multitasking development notes”
  15. 15. EARLIER iOS SUPPORT set the deployment target to the lowest you want to support set the base and active SDK to the latest stable available weakly link frameworks that may not exist on the deployment platform at runtime, make sure code that needs OS 4.0 features (including C blocks) doesnt get executed when running on earlier OS versions: NSClassFromString, [UIDevice currentDevice].multitaskingSupported, respondsToSelector , instancesRespondesToSelector are your friendsNico Tranquilli • July 2010 “iOS4 multitasking development notes”
  16. 16. SOME CODE SNIPPETS checking multitasking availability -(BOOL)isMultitaskingOS { BOOL bgSupport=NO; if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) ! ! bgSupport=[UIDevice currentDevice].multitaskingSupported; return bgSupport; } checking the runtime state of the app -(BOOL)isForeground { ! if (![self isMultitaskingOS]) ! ! return YES; ! UIApplicationState state = [UIApplication sharedApplication].applicationState; ! //return (state==UIApplicationStateActive || state==UIApplicationStateInactive ); ! return (state==UIApplicationStateActive); }Nico Tranquilli • July 2010 “iOS4 multitasking development notes”
  17. 17. SOME CODE SNIPPETS making sure an app is not suspended while completing a task in the background (uses C blocks and the Grand Central Dispatch) UIApplication *app=[UIApplication sharedApplication]; NSAssert(self->bgTask == UIInvalidBackgroundTask, nil); // beginBackgroundTaskWithExpirationHandler: marks the beginning of // a new long-running background task. bgTask = [app beginBackgroundTaskWithExpirationHandler: ^{ ! dispatch_async(dispatch_get_main_queue(), ^{ ! ! [app endBackgroundTask:self->bgTask]; ! ! self->bgTask = UIInvalidBackgroundTask; ! }); }]; ! dispatch_async(dispatch_get_main_queue(), ^{ ! // do something! ! // eg:while ([app backgroundTimeRemaining] > 1.0) { ; } ! ! ! [app endBackgroundTask:self->bgTask]; ! self->bgTask = UIInvalidBackgroundTask; });Nico Tranquilli • July 2010 “iOS4 multitasking development notes”
  18. 18. SOME CODE SNIPPETS background app relaunch by os due to a location event - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { ! // .... if ([launchOptions objectForKey:@"UIApplicationLaunchOptionsLocationKey"]]) { // application was (re)launched in response to an incoming location event ! } ! // .... ! }Nico Tranquilli • July 2010 “iOS4 multitasking development notes”
  19. 19. iPHONE iOS4 / SDK4.0 multitasking support from a developer’s perspective PlaceTrack has been available on the App Store since 09/2010 Nico Tranquilli www.tranquilli.orgNico Tranquilli • July 2010 “iOS4 multitasking development notes”