开发者

How to know if current device can have background mode

I am doing some tasks after having entered in background mode. I want to do these tasks only if I am in background mode so I did :

if ([[UIApplication sharedApplication] applicationState] == UIApplication开发者_StackOverflow中文版StateBackground)

But applicationState is only available in iOS 4.0 and later...

I wonder how this piece of code will work on iOS 3 for example.

  • How can I know if the device has iOS 4 ?
  • How can I avoid crash and exceptions for iOS < 4 ?

Thansk for your help

Kheraud


You can check whether the current iOS supports returning the current application state by using -respondsToSelector:

if ([[UIApplication sharedApplication] respondsToSelector:@selector(applicationState)] ){
  UIApplicationState state = [[UIApplication sharedApplication] applicationState];
}

You can determine whether multitasking support is available (even devices running iOS 4 or later may not have the hardware to support multitasking) by specifically checking for background support:

UIDevice* device = [UIDevice currentDevice];
BOOL backgroundSupported = NO;
if ([device respondsToSelector:@selector(isMultitaskingSupported)])
   backgroundSupported = device.multitaskingSupported;

You can retrieve the iOS version by using the following code (although you should not really rely on the following code to infer background support):

float osVersion=[[[UIDevice currentDevice] systemVersion] floatValue];

Finally, if you want to perform some tasks just after having entered background mode, you'll want to take advantage of the following event:

- (void)applicationDidEnterBackground:(UIApplication *)application

.. but note that your time will be very limited. You will have approximately five seconds to do whatever you want to do. In case you need more, you can try asking iOS for additional time:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    UIApplication*    app = [UIApplication sharedApplication];

    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Do the work associated with the task.

        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    });
}

Note that in this case, you might be granted more time by iOS (or not), but it's still a finite-length time.

Apple's Executing Code in the Background is a worth read.


I discovered this link very usefull to understand how to handle both 3.1 and >4.0 OS versions :

Developing iPhone Apps with iOS4 SDK, Deploying to 3.x Devices : Base SDK and iPhone OS Deployment Target

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜