我在数组中有几个对象,每个对象都有自己的日期。
我想在当前日期==对象日期时发出本地通知。
我有一些代码,我希望有人告诉我它是否有意义,如果它应该有效,我已经处理了委托和reloadData方法。
以下是代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"LiveIdent";
LiveViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
LiveMatchObject *item = [tableDataLiveMatch objectAtIndex:(int)([indexPath row]/2)];
if ([item isKindOfClass:[LiveMatchObject class]]) {
NSString * dateString = [NSString stringWithFormat: @"%@",item.matchDate];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"'Hoje ás' HH:mm 'horas"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
//// starts here the notification code
// create a timer to keep track of the current date
NSDate *now = [NSDate date];
NSDateFormatter *daterFormatter = [[NSDateFormatter alloc] init];
[daterFormatter setTimeZone:[NSTimeZone systemTimeZone]];
// if current date = date stored in the object then do this
if (myDate == now){
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = myDate;
localNotification.alertBody = @"Início da partida";
localNotification.alertAction = @"Show me the item";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadData" object:self];
}
NSArray *localNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
UILocalNotification *localNotification = [localNotifications objectAtIndex:indexPath.row];
[cell.textLabel setText:localNotification.alertBody];
[cell.detailTextLabel setText:[localNotification.fireDate description]];
return cell;
}
这是否应该是完全灾难?
P.S - 我无法测试,因为我从明天会发生的实况事件中读取,所以我必须等待,为自己看看。谢谢。
答案 0 :(得分:1)
是的,您的代码看起来不错,但您可以通过设置一些接近时间来测试本地通知,而不是等待明天这里是我在项目中使用的代码:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay: 16];
[components setMonth: 3];
[components setYear: 2014];
[components setHour: 10];
[components setMinute:32];
[components setSecond: 0];
[calendar setTimeZone: [NSTimeZone defaultTimeZone]];
NSDate *dateToFire = [calendar dateFromComponents:components];
希望这会对你有所帮助。