1

我在iPhone中使用UILocalNotification來創建鬧鐘。當我點擊UIButton時,計劃報警。我的問題是,當我點擊此按鈕時,即在創建本地通知時調用– application:didReceiveLocalNotification:。但是,只有在達到通知時間時才應調用– application:didReceiveLocalNotification:。我在模擬器和設備上都檢查過它,並得到了相同的結果。任何人都可以幫助我... ...提前感謝。在創建通知後立即調用Appdelegate函數'didreceivelocalnotification'

-(void)createalarm:(NSString *)datend_time:(NSString *)message//creating alarm 
{ 
NSLog(@"created!!!!!!!!!!!!!"); 
NSString *datestr = datend_time; 
NSString *textstr = message; 
NSDateFormatter *formatter = [[NSDateFormatter alloc]init]; 
[formatter setDateFormat:@"MM/dd/yyyy hh:mm a"];  
NSDate *alerttime = [formatter dateFromString:datestr]; 
UIApplication * app = [UIApplication sharedApplication];  

UILocalNotification *notification = [[UILocalNotification alloc] init]; 
if (notification) 
{ 
    notification.fireDate = alerttime; 
    //notification.timeZone = [NSTimeZone defaultTimeZone]; 
    notification.repeatInterval = 0; 
    notification.alertBody = textstr; 
    notification.soundName = UILocalNotificationDefaultSoundName;   
    [app scheduleLocalNotification:notification]; 

    [app presentLocalNotificationNow:notification];   
} 

} 


-(void)application:(UIApplication *)application didReceiveLocalNotification: (UILocalNotification *)notification 
{ 
NSLOG(@"delegate called")  
} 
+0

你的代碼在哪裏? –

回答

-1

這裏是NSLocalnotification的例子:

-(void) scheduleNotificationForDate: (NSDate*)date { 

/* Here we cancel all previously scheduled notifications */ 
[[UIApplication sharedApplication] cancelAllLocalNotifications]; 

UILocalNotification *localNotification = [[UILocalNotification alloc] init]; 

localNotification.fireDate = date; 
NSLog(@"Notification will be shown on: %@",localNotification.fireDate); 

localNotification.timeZone = [NSTimeZone defaultTimeZone]; 
localNotification.alertBody = [NSString stringWithFormat: 
           @"Your notification message"]; 
localNotification.alertAction = NSLocalizedString(@"View details", nil); 

/* Here we set notification sound and badge on the app's icon "-1" 
means that number indicator on the badge will be decreased by one 
- so there will be no badge on the icon */ 

localNotification.soundName = UILocalNotificationDefaultSoundName; 
localNotification.applicationIconBadgeNumber = -1; 

[[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; 
} 

確保您設置的日期不過去!

+0

我已經檢查過它。我確定我設定的日期不在過去。 – jjpp

+0

你可以發佈一些代碼和日誌嗎? – Resh32

1

這是因爲你叫

[app presentLocalNotificationNow:notification]; 

那麼就說明你創建後馬上通知。刪除這行代碼。

[app scheduleLocalNotification:notification];將工作得很好,並會在fireDate上發佈通知。