[英]iOS Timer run in background
我的應用程序需要定期調用方法。
即使應用程序已在后台運行,也應該執行此調用。
無論何時應用程序可以從后台恢復,應用程序可以在后台運行的時間都是未定義的。
我有一個類來管理計時器:
@protocol TimerDelegate <NSObject>
- (void)startTimerAction:(id)userInfo;
@end
@interface TimerController : NSObject{
NSTimer *repeatingTimer;
id <TimerDelegate> delegate;
}
+ (TimerController *)sharedInstance;
- (void)startTimerForSender:(id <TimerDelegate>)sender withTimeInterval:(NSTimeInterval)time;
- (void)stopTimer;
@end
執行:
#import "TimerController.h"
TimerController *singletonInstance;
@implementation TimerController
#pragma mark - Singleton
+ (TimerController *)sharedInstance {
if (singletonInstance == nil) {
singletonInstance = [[super allocWithZone:NULL] init];
}
return singletonInstance;
}
+ (id)allocWithZone:(NSZone *)zone
{
return [self sharedInstance];
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
#pragma mark - Public
- (void)startTimerForSender:(id <TimerDelegate>)sender withTimeInterval:(NSTimeInterval)time
{
if (repeatingTimer) {
[self stopTimer];
}
if (sender) {
delegate = sender;
}
if (time > 0.0) {
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(targetMethod:)
userInfo:[self userInfo] repeats:YES];
repeatingTimer = timer;
}
}
- (void)stopTimer
{
if (repeatingTimer) {
[repeatingTimer invalidate];
repeatingTimer = nil;
}
}
- (NSDictionary *)userInfo
{
return @{@"StartDate" : [NSDate date]};
}
- (void)targetMethod:(NSTimer*)theTimer
{
if (delegate && [delegate respondsToSelector:@selector(startTimerAction:)]) {
[delegate startTimerAction:[repeatingTimer userInfo]];
}
}
@end
我用這種方式使用TimerController
類:
-(void)viewDidLoad{
[super viewDidLoad]
TimerController *timerC = [TimerController sharedInstance];
[timerC startTimerForSender:self withTimeInterval:30];
}
#pragma mark - TimerDelegate
- (void)startTimerAction:(id)userInfo
{
NSLog(@"Method called");
}
我可以每隔30秒讀取一次NSLog
條目。 將應用程序置於后台使定時器停止,並且當應用程序恢復計時器正常工作時,它不會每30秒寫入一次日志。
雖然應用程序在后台,但我需要每隔30秒調用一次方法。
我讀到了這個問題: 計時器處於后台模式
我必須能夠向AppStore提交申請。
謝謝
- (void)applicationDidEnterBackground:(UIApplication *)application
{
bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
// Clean up any unfinished task business by marking where you
// stopped or ending the task outright.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do the work associated with the task, preferably in chunks.
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
}
要在后台持續運行您的應用程序,您需要在plist中為所需的背景模式注冊您的應用程序
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.