iOS后台运行

让程序在后台长久运行的示例代码如下:

后台运行

使用block的另一个用处是可以让程序在后台较长久的运行。在以前,当app被按home键退出后,app仅有最多5秒钟的时候做一些保存或清理资源的工作。但是应用可以调用UIApplication的beginBackgroundTaskWithExpirationHandler方法,让app最多有10分钟的时间在后台长久运行。这个时间可以用来做清理本地缓存,发送统计数据等工作。

// AppDelegate.h文件
@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;

// AppDelegate.m文件
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [self beingBackgroundUpdateTask];
    // 在这里加上你需要长久运行的代码
    [self endBackgroundUpdateTask];
}

- (void)beingBackgroundUpdateTask
{
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
}

- (void)endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}

安排Local Notification的传递

UILocalNotification类提供了一种方法来传递local notifications。和push notifications需要设置remote server不同,local notifications 在程序中安排并在当前的设备上执行。满足如下条件可以使用该能力:

1、一个基于时间的程序,可以在将来特定的时间让程序post 一个alert,比如闹钟

2、一个在后台运行的程序,post 一个local notification去引起用户的注意

为了安排local notification 的传递,需要创建一个UILocalNotification的实例,并设置它,使用UIApplication类方法来安排它。Local notification对象包含了所要传递的类型(sound,alert,或者badge)和时间何时呈现) 。UIApplication类方法提供选项去确定是立即传递还是在指定的时间传递。

- (void)scheduleAlarmForDate:(NSDate*)theDate  
{  
    UIApplication* app = [UIApplication sharedApplication];  
    NSArray* oldNotifications = [app scheduledLocalNotifications];  
    // Clear out the old notification before scheduling a new one.  
    if ([oldNotifications count] > 0)  
        [app cancelAllLocalNotifications];  
    // Create a new notification.  
    UILocalNotification* alarm = [[UILocalNotification alloc] init];  
    if (alarm)  {  
        alarm.fireDate = theDate;  
        alarm.timeZone = [NSTimeZone defaultTimeZone];  
        alarm.repeatInterval = 0;  
        alarm.soundName = @"alarmsound.caf";  
        alarm.alertBody = @"Time to wake up!";  
        [app scheduleLocalNotification:alarm];  
    }  
} 

(可以最多包含128个 local notifications active at any given time, any of which can be configured to repeat at a specified interval.)如果在调用该notification的时候,程序已经处于前台,那么application:didReceiveLocalNotification:方法将取而代之。

 

posted @ 2015-05-14 17:38  CodingTom  阅读(235)  评论(0编辑  收藏  举报