代码之家  ›  专栏  ›  技术社区  ›  Chandrasekaran Dinesh

在一天中的某个时间发送本地通知

  •  0
  • Chandrasekaran Dinesh  · 技术社区  · 10 年前

    我想从数组中获取一个随机字符串,然后每天早上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。如何解决此问题?

    1 回复  |  直到 10 年前
        1
  •  0
  •   Markus Dheus    10 年前

    您需要将“arrayOfOurQuotes”实现为App委托的属性,而不是视图控制器。当视图消失时,视图控制器和您的阵列将不再存在——如果您已经进入了背景,这是很明显的情况。