iOS进入后台长时间运行后台任务

@property (nonatomic, strong) NSTimer *reStartSMTimer;



- (void)beingBackgroundUpdateTask;

- (void)endBackgroundUpdateTask;



- (void)applicationDidEnterBackground:(UIApplication *)application

{

DDLogInfo( @"applicationDidEnterBackground" );

// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 

// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        [self beingBackgroundUpdateTask];

    });

    


    if (self.reStartSMTimer )

    {

        [self.reStartSMTimer invalidate];

        self.reStartSMTimer = nil;

    }

    NSTimeInterval backgroundTimeRemaining = [[UIApplication sharedApplication] backgroundTimeRemaining];

    NSTimeInterval interval = backgroundTimeRemaining > 2 * 60.f ? 2* 60.f: backgroundTimeRemaining;

    self.reStartSMTimer =   [NSTimer scheduledTimerWithTimeInterval: interval

                                                             target:self

                                                           selector:@selector(timerMethod:) userInfo:nil

                                                           repeats:NO];

}



- (void) timerMethod:(NSTimer *)paramSender

{

    [self endBackgroundUpdateTask];

}




- (void)beingBackgroundUpdateTask

{

    __weak AppDelegate * weakSelf = self;

    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{

        [weakSelf endBackgroundUpdateTask];

    }];

}


- (void)endBackgroundUpdateTask

{

    if (self.reStartSMTimer )

    {

        [self.reStartSMTimer invalidate];

        self.reStartSMTimer = nil;

    }

    

    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];

    self.backgroundUpdateTask = UIBackgroundTaskInvalid;

}


- (void)applicationWillEnterForeground:(UIApplication *)application

{

DDLogInfo( @"applicationWillEnterForeground" );

// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.

    

    if (self.backgroundUpdateTask != UIBackgroundTaskInvalid)

    {

        [self endBackgroundUpdateTask];

    }

}

你可能感兴趣的:(iphone/object-c)