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