倒计时+后台定位

35318D2B5E4AE17855DA7779B5346BBF.png

程序进入后台倒计时

    #import "ViewController.h"
    @interface ViewController () {
             dispatch_source_t _processingQueueSource;
    }
    @property(assign,nonatomic) NSInteger timeInterval;
    @property (atomic, assign, getter=isRunning) BOOL running;
    @property (weak, nonatomic) IBOutlet UISlider *slider;

    @end

    @implementation ViewController

     - (void)viewDidLoad {
             [super viewDidLoad];

            self.slider.maximumValue = 50.0f;
            self.slider.minimumValue = 0.0f;
            self.timeInterval = 50.0f;
            NSInteger totalTime =  self.timeInterval;
           _processingQueueSource =       dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0,
                                                dispatch_get_main_queue());
            __block NSUInteger totalComplete = 0;
            dispatch_source_set_event_handler(_processingQueueSource, ^{

            NSUInteger value = dispatch_source_get_data(_processingQueueSource);
            totalComplete += value;
            if (self.timeInterval<=0) {
                  _processingQueueSource = nil;
            }else{
                 self.timeInterval --;
             } 
              _slider.value = totalComplete;
            });
          //分派源创建时默认处于暂停状态,在分派源分派处理程序之前必须先恢复。
           [self resume];

      //恢复源后,就可以通过dispatch_source_merge_data向Dispatch Source(分派源)发送事件:
            dispatch_queue_t queue =          dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
            for (NSUInteger index = 0; index <totalTime; index++) {
                     dispatch_source_merge_data(_processingQueueSource, 1);
                    usleep(1000000);//1秒
              }
        });

     }


   - (void)resume {
              if (self.running) {
                   return;
              }
            self.running = YES;
            dispatch_resume(_processingQueueSource);
   }

   - (void)pause {
         if (!self.running) {
                 return;
         }
        self.running = NO;
        dispatch_suspend(_processingQueueSource);
   }

如何让程序在后台运行

     - (void)applicationDidEnterBackground:(UIApplication *)application {

       //后台运行
       __block    UIBackgroundTaskIdentifier bgTask;
       bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
            dispatch_async(dispatch_get_main_queue(), ^{
               if (bgTask != UIBackgroundTaskInvalid) {
                           bgTask = UIBackgroundTaskInvalid;
                }
            });
       }];
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容