Swift 3 - How to make timer work in background

后端 未结 9 458
忘掉有多难
忘掉有多难 2020-11-30 09:43

i am trying to do an application which can make a timer run in background.

here\'s my code:

let taskManager = Timer.scheduledTimer(timeInterval: 10,          


        
9条回答
  •  星月不相逢
    2020-11-30 10:34

    ============== For Objective c ================

    create Global uibackground task identifier.

    UIBackgroundTaskIdentifier bgRideTimerTask;

    now create your timer and add BGTaskIdentifier With it, Dont forget to remove old BGTaskIdentifier while creating new Timer Object.

     [timerForRideTime invalidate];
     timerForRideTime = nil;
    
     bgRideTimerTask = UIBackgroundTaskInvalid;
    
     UIApplication *sharedApp = [UIApplication sharedApplication];       
     bgRideTimerTask = [sharedApp beginBackgroundTaskWithExpirationHandler:^{
    
                                }];
     timerForRideTime =  [NSTimer scheduledTimerWithTimeInterval:1.0
                                                                                     target:self
                                                                                   selector:@selector(timerTicked:)
                                                                                   userInfo:nil
                                                                                    repeats:YES]; 
                                                       [[NSRunLoop currentRunLoop]addTimer:timerForRideTime forMode: UITrackingRunLoopMode];
    

    Here this will work for me even when app goes in background.ask me if you found new problems.

提交回复
热议问题