繁体   English   中英

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

[英]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];

我的其他View Controller中有一个数组。 我确实导入了视图控制器。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM