【问题标题】:iPhone: Notification Center TroubleiPhone:通知中心故障
【发布时间】:2012-01-18 22:51:39
【问题描述】:

我编写了一个应用程序,允许用户在 UITextField 中输入数据,其中一个允许他们输入特定日期。我试图在距离日期 15 小时后在 iPhone 通知中心显示警报,即使应用程序根本没有运行。

编辑:新代码-

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { UILocalNotification *localNotif = [[UILocalNotification alloc] init];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMdd"];
NSDate *eventDate=[dateFormatter dateFromString:eventDateField.text];

localNotif.fireDate = [eventDate dateByAddingTimeInterval:-15*60*60];
localNotif.timeZone = [NSTimeZone defaultTimeZone];


localNotif.alertBody = @"Event Tomorrow!";

localNotif.alertAction = @"Show me";

localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 0;
[[UIApplication sharedApplication]presentLocalNotificationNow:localNotif];

}

【问题讨论】:

  • 抱歉有点苛刻,但您缺少一些非常基本(和关键)的基础知识。帮自己一个忙,学习它们;它不会花费很长时间,最终会为您节省大量时间和挫败感。我可以推荐的一本非常好的书是iOS Programming: The Big Nerd Ranch Guide。它写得很好,涵盖了基础知识(也特别是您所询问的内容),并包含很好的示例。帮自己一个忙,得到它,阅读它,做练习。不会花很长时间,但会很有帮助。
  • 谢谢你,fzwo,是的,我在这里确实有点超前了。我今天会研究那本书,谢谢!

标签: iphone xcode notifications nsdate


【解决方案1】:

您想将消息dateByAddingTimeInterval: 发送给谁?没有人。你需要一个消息的接收者,一个可以运行该方法的对象。

[[NSDate date] dateByAddingTimeInterval: -20*60];

NSDate date 是当前日期和时间)。

【讨论】:

  • 太棒了,非常感谢。我的新代码现在看起来像这样:localNotif.fireDate = [[NSDate date] dateByAddingTimeInterval: -20*60]; 那么,通知中心是否会自动检测用户在该视图控制器的文本字段中输入的日期,以及应用程序未运行的时间?抱歉这些问题,我还是个新手。
  • 不,没有人会检测到用户输入的日期。你必须自己做。检查NSDateFormatter 的文档。你要找的方法是dateFromString:
【解决方案2】:

将从文本字段获得的日期存储在NSDate 对象eventDate 中。您还需要设置日期和时间。您收到该错误的原因是 dateByAddingTimeInterval: 应该在 NSDate 对象上调用,它本身不是标识符。将本地通知的fireDate设置为

localNotif.fireDate=[eventDate dateByAddingTimeInterval:-15*60*60];

这将返回事件前 15 小时的日期。

编辑:您需要创建一个NSDateFormatter 对象并将其格式设置为它在meetingDateField 中的存储方式。然后使用dateFromString: 从文本字段中获取NSDate

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm'/'dd'/'yyyy"];
NSDate *eventDate=[dateFormatter dateFromString:meetingDateField.text];

【讨论】:

  • 太棒了,非常感谢。但是我在使用 NSDate 对象从文本字段中获取日期时遇到了一些问题。我是这样设置的:NSDate *eventDate = [NSDate meetingDateField]; localNotif.fireDate = [eventDate dateByAddingTimeInterval:-480*60];(会议日期是他们输入日期的文本字段)
  • @Joey502 尝试编辑后的答案。也看看developer.apple.com/library/mac/#documentation/Cocoa/Reference/…
  • 太棒了,谢谢,但是使用上面的新代码,我收到错误“选择器“meetingDateField”没有已知的类方法
  • @Joey502 您似乎对对象和消息有误解。您可以将消息传递给 meetingDateField。您不能将 meetingDateField(object) 作为消息传递给 NSDate 类。在继续之前,您应该阅读基础知识。
  • @Joey502 不客气。您应该返回一个 BOOL。只需添加 return YES;
【解决方案3】:

为了调用[-dateByAddingTimeInterval:],你必须有一个 NSDate 对象。在您上面的代码中,您没有。它应该类似于:

NSDate* now = [NSDate date];
localNotif.fireDate = [now dateByAddingTimeInterval:20*60];

【讨论】:

    猜你喜欢
    • 2020-10-17
    • 2016-09-09
    • 1970-01-01
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多