Search code examples
cocos2d-iphone

How to Schedule Local Notification Once in a Day at Random Time With Random Text


I Want Random Local notification once every 24 hours.
I know , i Can have Daily Local Notification Using this :

UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = fireDate;
localNotification.timeZone = [NSTimeZone defaultTimeZone];  
localNotification.repeatInterval = NSDayCalendarUnit;
localNotification.alertBody = alertText;
localNotification.alertAction = alertAction;    

// Schedule it with the app

[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[localNotification release];

But ,With This I can Have Same Time Every Day ,But How can I have a Random Time EveryDay. Please Help !

Even, Is this Possible ?


Solution

  • According to UILocalNotification class reference you could schedule up to 64 local notifications to fire at exact time. It is enough to cover a couple months of random timed notifications since every app launch. Here is a sample:

    - (void)scheduleLocalNotifications
    {
        [[UIApplication sharedApplication] cancelAllLocalNotifications];
    
        static NSInteger dayInSeconds = 60*60*24;
        NSInteger now = (NSInteger)[NSDate timeIntervalSinceReferenceDate];
        NSInteger tomorrowStart = now - now % dayInSeconds + dayInSeconds;
        for (int q=0; q<64; ++q)
        {
            NSInteger notificationTime = tomorrowStart + q*dayInSeconds + rand()%dayInSeconds;
            NSDate * notificationDate = [NSDate dateWithTimeIntervalSinceReferenceDate:notificationTime];
            NSLog(@"date %@", notificationDate);
    
            UILocalNotification * notification = [UILocalNotification new];
            notification.fireDate = notificationDate;
            notification.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
            notification.soundName = UILocalNotificationDefaultSoundName;
            notification.alertBody = @"Hello!";
            [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        }
    }