[英]iOS Timer in the background
我想在我的iOS應用程序中啟動計時器,當應用程序在后台運行時以及應用程序關閉時。 計時器必須每30分鍾檢查一次新的通知。 在計時器功能中,他們每隔30分鍾調用另一個函數showNotification()。
我怎么做這個計時器,當應用程序沒有在后台運行/運行時,我必須在哪個地方調用計時器。
AFAIK在后台(生產中)180s后無法運行NSTimer。
編輯:如果啟用后台模式,則最多可以獲得10分鍾。 你可以了解更多,例如。 在這里 。
當應用程序不在前台時,不可能做到100%確定。 您可以使用后台提取定期喚醒,但無法控制何時發生。
雖然有一些技術上的解決方法,甚至可能是一些hacky解決方案(在后台播放靜音音頻),但聽起來我的問題可以在不使用定時器和后台獲取的情況下解決。
只需實現遠程通知 。 當您的iOS收到應用通知時,它會喚醒應用並讓它處理一段時間。 然后,您可以控制向用戶顯示的通知,並可能在后台加載一些數據。
從廣義上講,您需要:
Write this both methos in your Appdelegate.m file
//For Objective c
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self TimerMethod];
}
-(void)TimerMethod
{
//Every 30 minute call the functions
_timer=[NSTimer scheduledTimerWithTimeInterval:1800.0f target:self selector:@selector(updateMethod:) userInfo:nil repeats:YES];
}
- (void)updateMethod:(NSTimer *)theTimer
{
NSLog(@"Timer set now");
}
//For Swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool
{
self.TimerMethod()
}
func TimerMethod()
{
var timer = NSTimer.scheduledTimerWithTimeInterval(1800, target: self, selector: "updateMethod", userInfo: nil, repeats: true)
}
func updateMethod()
{
print("set timer now")
}
將此代碼添加到appdeleage.swift中
var backgroundUpdateTask: UIBackgroundTaskIdentifier = 0
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
return true
}
func applicationWillResignActive(application: UIApplication) {
self.backgroundUpdateTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
self.endBackgroundUpdateTask()
})
}
func endBackgroundUpdateTask() {
UIApplication.sharedApplication().endBackgroundTask(self.backgroundUpdateTask)
self.backgroundUpdateTask = UIBackgroundTaskInvalid
}
func applicationWillEnterForeground(application: UIApplication) {
self.endBackgroundUpdateTask()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.