2016-08-15 49 views
-1

早上好, 如何通知本地通知每兩週(14天)通知。如何每兩週通知UILocalNotification

- (void)applicationDidEnterBackground:(UIApplication *)application { 

    timer = [NSTimer scheduledTimerWithTimeInterval:60*60*24*14 target:self selector:@selector(getNotifiedForTwoWeeks:) userInfo:nil repeats:YES]; 


} 

-(void)getNotifiedForTwoWeeks:(id)userinfo{ 

     // Schedule the notification 
    UILocalNotification* localNotification = [[UILocalNotification alloc] init]; 
    localNotification.fireDate = [NSDate date]; 
    localNotification.alertBody = @"Notification Message"; 
    localNotification.alertAction = @"Show me the item"; 
    localNotification.timeZone = [NSTimeZone timeZoneWithName:@"GMT"]; 
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; 
} 

請讓我知道這個實現是否正確? 有沒有其他辦法可以做到最好,每兩週通知LocalNotification消息。

您的寶貴意見非常感謝!

+0

通過聲明fireDaterepeatInterval屬性我不知道這是什麼'NSTimer'是,作爲唯一的去工作,如果應用程序是活躍2周。您應該將'fireDate'更新爲將來的某個日期(並且您應該執行'NSCalendar' calandrical計算而不是60 * 60 * 24 * 12)。請參閱http://stackoverflow.com/a/27424355/1271826。 – Rob

+0

如果是每週或每月,而不是每兩週,您可以使用'repeatInterval',但是每兩週,我想您必須自己安排它們,如該答案中所示。 – Rob

+0

@NSTimer用於計劃TimeInterval以觸發指定通知聲明方法的特定方法。 – kiran

回答

0

當您的應用程序進入後臺時,系統將在一段時間後掛起並且您的NSTimer不會計劃。 所以,你可以計劃每14天通知,UILocalNotification

UILocalNotification* localNotification = [[UILocalNotification alloc] init]; 
localNotification.fireDate = [NSDate dateByAddingTimeInterval:60*60*24*14]; 
localNotification.alertBody = @"Notification Message"; 
localNotification.alertAction = @"Show me the item"; 
localNotification.timeZone = [NSTimeZone timeZoneWithName:@"GMT"]; 
localNotification.repeatInterval = NSDayCalendarUnit; 

[[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; 
+0

不用說,對於計劃爲60 * 60 * 24 * 14的計時器,'beginBackgroundTaskWithName'沒有用處。無論如何,整個計時器事件對於這個用例來說都是死衚衕的。好幾分鐘,不過幾周。 – Rob

+0

是的,你是對的 – iSashok