• 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:方法将取而代之。

  • 相关阅读:
    F. Journey
    D. Divide
    C. Counting Pair
    A. A Big Dinner
    E
    D -Sale
    第十三课 历史记录画笔工具
    第十二课 文字工具
    第十一课 模糊工具、海绵工具、仿制图章工具
    第十课 切片工具 修复画笔工具 修补工具 颜色替换工具
  • 原文地址:https://www.cnblogs.com/tomblogblog/p/4503944.html
Copyright © 2020-2023  润新知