2012-11-09 72 views
4

我想知道,如果有可能以某種方式「喚醒」後臺任務,以便快速檢查網絡中的某個任務。我認爲這可以通過UILocalNotification完成,但是,無論我嘗試了什麼,我都無法在應用程序處於後臺時使didReceiveLocalNotification執行任何操作。啓動後,我立即通過按Home按鈕關閉應用程序(本地通知發生延遲10秒鐘)。此代碼工作完全當應用程序在前臺,而只是一種坐在那裏......是否可以使用UILocalNotification喚醒後臺任務

在應用程序委託頭文件:

UILocalNotification *localNotif; 

爲了測試,我設置了本地通知在快速射擊appDelegate啓動。

localNotif = [[UILocalNotification alloc] init]; 
localNotif.fireDate = [NSDate dateWithTimeIntervalSinceNow:10]; // the date you want the notification to fire. 
localNotif.timeZone = [NSTimeZone defaultTimeZone]; 
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif]; 

NSLog(@"setup the timer for 10 seconds"); 





- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { 
UIApplicationState state = [application applicationState]; 
NSLog(@"getting kicked"); 
if (state == UIApplicationStateInactive) { 

    // Application was in the background when notification was delivered. 

    NSLog(@"INACTIVE.."); 
} else { 
    NSLog(@"ACTIVE.."); 

} 

}

回答

5

用戶有兩個選擇:#1)他們希望看到你的應用程序的通知。 #2)如果爲您的應用啓用了通知,他們是否想要點擊通知來啓動您的應用。如果他們確實接受通知並在應用程序處於後臺時打開通知,則會調用application:didReceiveLocalNotification。爲了清楚起見,用戶必須接受通知(例如滑動通知下方的滑塊),否則將調用NOTHING。

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { 
    NSLog(@"%@", notification); 
} 

如果您的應用程序已終止application:didFinishLaunchingWithOptions:被稱爲 -

- (BOOL)application:(UIApplication *) 
application didFinishLaunchingWithOptions: 
(NSDictionary *)launchOptions { 
    UILocalNotification *theNotification = 
     [launchOptions 
     objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]; 
    NSLog(@"%@", theNotification); 

    return YES; 
} 
+1

只是讓我明白了,didReceiveLocalNotification執行本地通知後只有後有人刷卡,而不是之前,如果應用程序在後臺(提供通知爲應用程序打開).. – geekyaleks

+0

正是......這是通知的侷限性......它需要一個真正的用戶與他們進行交互。 –

相關問題