2017-02-28 15 views
0

我创建了一个localNotification来启动一个消息,并且它不会在好时刻被调用。奇怪的是,当我把日期在未来,它永远不会触发它,但如果我把一个过去的日期,它在推出应用程序的启动它...localNotification运行不正常。函数didReceiveLocalNotification没有在好时刻被调用

主要功能:

... 
NSDateComponents *comps = [NSDateComponents new]; 
    [comps setDay:28]; 
    [comps setMonth:02]; 
    [comps setYear:2017]; 
    [comps setHour:16]; 
    [comps setMinute:50]; 
    [comps setSecond:00]; 

    NSDate *alarmDate = [[NSCalendar currentCalendar] dateFromComponents:comps]; 
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
    // or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 

    NSDate *currentDate= [NSDate date]; 
    UILocalNotification *localNotification = [[UILocalNotification alloc] init]; 

    // Set the fire date/time 
    [localNotification setFireDate:alarmDate]; 
    [localNotification setTimeZone:[NSTimeZone defaultTimeZone]]; 

    localNotification.applicationIconBadgeNumber=1; 

    // Setup alert notification 
    [localNotification setAlertAction:@"Open App"]; 
    // [localNotification setAlertBody:[randonQuotesDic objectForKey:@"Rajneesh"]]; 
    [localNotification setAlertBody:@"You had set a Local Notification on this time"]; 

    localNotification.soundName=UILocalNotificationDefaultSoundName; 
    [localNotification setHasAction:YES]; 
    UIApplication *app=[UIApplication sharedApplication]; 
    [app scheduleLocalNotification:localNotification]; 
... 

功能接收本地通知:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification 
{ 
    UIApplicationState state = [application applicationState]; 
    // check state here 

    if(state ==UIApplicationStateBackground){ 

    } 
    dispatch_async(dispatch_get_main_queue(), ^{ 

     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Wake" message:notification.alertBody delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]; 
     [alertView show]; 
    }); 
} 

它不能正常工作...

回答

0

下面是答案:

您必须对其进行简单授权。您必须在初始化localNotification之前在主函数中放置该行:

UIUserNotificationType types = UIUserNotificationTypeBadge | 
    UIUserNotificationTypeSound | UIUserNotificationTypeAlert; 

    UIUserNotificationSettings *mySettings = 
    [UIUserNotificationSettings settingsForTypes:types categories:nil]; 

    [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings]; 
相关问题