在一天中的特定时间发送本地通知

Send local notification at a certain time of the day

我想从数组中获取一个随机字符串,然后在每天早上 7 点显示它。

这是我的 AppDelegate.m

中的代码
-(void)applicationDidEnterBackground:(UIApplication *)application
{ 

    QuoteTableViewController *quoteVC;
        int randomlyGeneratedNumber;
        randomlyGeneratedNumber =arc4random()%[quoteVC.arrayOfOurQuotes count];
        NSString *stringOfTheDay = [[NSString alloc] init];
        stringOfTheDay = [quoteVC.arrayOfOurQuotes objectAtIndex:randomlyGeneratedNumber];
        NSLog(@"%@",stringOfTheDay);

        NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

        NSDateComponents *componentsForReferenceDate = [calendar components:(NSCalendarUnitDay | NSCalendarUnitYear | NSCalendarUnitMonth ) fromDate:[NSDate date]];

        [componentsForReferenceDate setDay:9];
        [componentsForReferenceDate setMonth:11];
        [componentsForReferenceDate setYear:2012];

        NSDate *referenceDate = [calendar dateFromComponents:componentsForReferenceDate];
        NSDateComponents *componentsForFireDate = [calendar components:(NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond ) fromDate: referenceDate];

        [componentsForFireDate setHour:7];
        [componentsForFireDate setMinute:0];
        [componentsForFireDate setSecond:0];

        NSDate *fireDateOfNotification = [calendar dateFromComponents:componentsForFireDate];

        // Create the notification

        UILocalNotification *notification = [[UILocalNotification alloc] init];
        if (notification) {
            notification.fireDate = fireDateOfNotification;
            notification.timeZone = [NSTimeZone localTimeZone];
            notification.repeatInterval = 0;
            notification.alertBody = [NSString stringWithFormat:stringOfTheDay];
            notification.soundName = UILocalNotificationDefaultSoundName;
            notification.applicationIconBadgeNumber = 1;
            [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        }
}

当我运行代码

时,这一行有错误
randomlyGeneratedNumber =arc4random()%[quoteVC.arrayOfOurQuotes count];

我的另一个视图控制器中有一个数组。我确实导入了视图控制器。

编辑: 数组内部有字符串,但是当导入到应用程序委托中时它变为 0。如何解决这个问题?

您需要将 'arrayOfOurQuotes' 实现为应用程序委托的 属性 而不是视图控制器。当视图消失时,视图控制器和您的数组将不再存在 - 如果您已经进入后台,显然是这种情况。