Skip to content

Instantly share code, notes, and snippets.

@edom18
Created May 28, 2015 07:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edom18/16560e03653376987b11 to your computer and use it in GitHub Desktop.
Save edom18/16560e03653376987b11 to your computer and use it in GitHub Desktop.
[Objective-C] バックグラウンドで継続して処理を実行する ref: http://qiita.com/edo_m18/items/52fb7190d4285aabc1c9
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) UIBackgroundTaskIdentifier bgid;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[NSNotificationCenter.defaultCenter addObserver:self
selector:@selector(willResignActive:)
name:UIApplicationWillResignActiveNotification
object:nil];
[NSNotificationCenter.defaultCenter addObserver:self
selector:@selector(didBecomeActive:)
name:UIApplicationDidBecomeActiveNotification
object:nil];
[self update];
}
- (void)update
{
if (self.timer) {
[self.timer invalidate];
self.timer = nil;
}
self.timer = [NSTimer scheduledTimerWithTimeInterval:3
target:self
selector:@selector(update)
userInfo:nil
repeats:YES];
NSLog(@"timer");
}
- (void)willResignActive:(NSNotification *)notification
{
NSLog(@"resign");
UIApplication *app = UIApplication.sharedApplication;
self.bgid = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:self.bgid];
self.bgid = UIBackgroundTaskInvalid;
}];
}
- (void)didBecomeActive:(NSNotification *)notification
{
NSLog(@"become");
[UIApplication.sharedApplication endBackgroundTask:self.bgid];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment