在iPhone中创建基于时间的提醒应用程序

时间:2012-01-17 09:57:44

标签: iphone objective-c xcode nsdate date-comparison

我正在研究基于时间的提醒应用。其中用户输入他的提醒和提醒时间。问题是如何连续比较当前时间和用户定义的时间。任何示例代码都会有很大帮助。因为我坚持这一点。

2 个答案:

答案 0 :(得分:15)

比较当前时间与用户定义的时间不是正确的设计模式。

UIKit提供了NSLocalNotification对象,它是您的任务的更高级抽象。

下面是一段代码,用于在选择的时间创建和安排本地通知:

    UILocalNotification *aNotification = [[UILocalNotification alloc] init];
    aNotification.fireDate = [NSDate date];
    aNotification.timeZone = [NSTimeZone defaultTimeZone];

    aNotification.alertBody = @"Notification triggered";
    aNotification.alertAction = @"Details";

    /* if you wish to pass additional parameters and arguments, you can fill an info dictionary and set it as userInfo property */
    //NSDictionary *infoDict = //fill it with a reference to an istance of NSDictionary;
    //aNotification.userInfo = infoDict;

    [[UIApplication sharedApplication] scheduleLocalNotification:aNotification];
    [aNotification release];

此外,请务必将AppDelegate设置为在启动时和应用程序的正常运行时期间响应本地通知(如果您希望在应用程序处于前台时收到通知):

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    UILocalNotification *aNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsLocalNotificationKey]; 

    if (aNotification) {
        //if we're here, than we have a local notification. Add the code to display it to the user
    }


    //...
    //your applicationDidFinishLaunchingWithOptions code goes here
    //...


        [self.window makeKeyAndVisible];
    return YES;
}



- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {

        //if we're here, than we have a local notification. Add the code to display it to the user


}

Apple Developer Documentation的更多详情。

答案 1 :(得分:2)

为什么不使用您可以在指定时间内设置的NSLocalNotification,就像日历事件一样。或者,您可以使用EKEventKit

将日历事件添加到用户日历

local notifications的教程。

event kit的教程。