【问题标题】:Issue to set random message in alert body every day on local notification iOS在本地通知 iOS 上每天在警报正文中设置随机消息的问题
【发布时间】:2014-06-23 06:38:25
【问题描述】:

我使用以下代码在每天上午 8:00 使用本地通知从 myArray(NSArray) 生成随机消息。但它不起作用。我每天都会收到相同的消息,即如果今天我收到“测试 3”,那么第二天早上 8:00 我将收到与“测试 3”相同的消息。我想从该数组中生成随机消息。

我不知道我的代码有什么问题。下面是我生成随机消息的示例代码:

[[UIApplication sharedApplication] cancelAllLocalNotifications];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

// Get the current date
 NSDate *Systemdate = [NSDate date];


// Break the date up into components
NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit )
                                               fromDate:Systemdate];

// Set up the fire time
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:8];

// Notification will fire in one minute
[dateComps setMinute:0];
[dateComps setSecond:0];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];


NSArray *myArry = [NSArray arrayWithObjects:@"Test 1", @"Test 2",@"Test 3",@"Test 4",@"Test 5",@"Test 6", nil];

id randomObj = nil;
int randomIndex;
if([myArry count]>0){

    randomIndex = arc4random() % [myArry count];
    randomObj = [myArry objectAtIndex:randomIndex];
}


UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
    return;


// Notification details
localNotif.alertBody = [NSString stringWithFormat:@"%@", randomObj];


localNotif.fireDate = itemDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];


// Set the action button
localNotif.alertAction = @"View Alert";

localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
localNotif.repeatInterval = NSDayCalendarUnit;

// Specify custom data for the notification
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"someValue" forKey:@"someKey"];
localNotif.userInfo = infoDict;

// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];

谢谢你的建议!!

【问题讨论】:

  • 您的代码对我来说看起来不错。你用randomObj做什么?
  • 它从该数组中生成随机对象。
  • 好吧,代码是正确的,所以我想知道你对所选字符串做了什么让你认为它不起作用。我认为这就是错误所在。
  • 我不知道如何将 alertBody 设置为每天上午 8:00 从该数组生成随机消息。你能告诉我如何按照我的意愿管理那个 alertBody 吗??
  • 每天我都会收到类似“Test 4”的消息。我想要随机的。

标签: ios objective-c uilocalnotification nscalendar nstimeinterval


【解决方案1】:

我认为您的问题出在“localNotif.repeatInterval = NSDayCalendarUnit;”,您每天都在重新安排相同的通知,这就是您拥有相同内容的原因。如果您希望每次都使用不同的文本,则必须为每个随机值创建单独的通知对象并手动安排它们。例如,您可以安排 10 个或更多活动,将最后安排的日期保存在用户默认值中,并进行一些逻辑以在最后保存日期前 2 天或类似的时间重新安排另外 10 个或更多。 您需要对此进行测试,理论上它看起来不错并且应该可以工作。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2012-06-30
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    相关资源
    最近更新 更多