UILocalNotification 即使日期已过,也会继续触发

UILocalNotification keeps firing even if the date was in the past

您好,希望有人能帮我解决这个问题。我还是 ios 开发的新手。我正在测试 UILocalNotification,我能够设置 firedate 并且一切正常,但如果 firedate 过去了,本地通知会立即触发。此外,每次我退出应用程序时,通知都会再次出现在通知中心。无论如何要确保只有在日期设置为未来时才会触发本地通知?我搜索了 SO 但我找不到我的答案。任何帮助将不胜感激。

这是viewDidLoad方法中的代码

class ViewController: UIViewController {


    var time : NSDate?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


        var comp = NSDateComponents()
        comp.year = 2015
        comp.month = 01
        comp.day = 20
        comp.hour = 16
        comp.minute = 00
        var calender = NSCalendar.currentCalendar()

        time = calender.dateFromComponents(comp)

        var notification = UILocalNotification()
        notification.alertBody = "this works"
        notification.fireDate = time
        notification.timeZone = NSTimeZone.defaultTimeZone()



        UIApplication.sharedApplication().scheduleLocalNotification(notification)
    }

这是AppDelegate中的代码

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        let notificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge
        let notificationSetiings = UIUserNotificationSettings(forTypes: notificationType, categories: nil)
        UIApplication.sharedApplication().registerUserNotificationSettings(notificationSetiings)
        return true
    }

如果您将 fireDate 设置为过去的日期,通知将立即触发。 Apple 在他们的 UILocalNotification documentation.

中进行了很好的设计和记录

fireDate Property

The date and time when the system should deliver the notification. Declaration

Swift

@NSCopying var fireDate: NSDate?

Objective-C

@property(nonatomic, copy) NSDate *fireDate

Discussion

The fire date is interpreted according to the value specified in the timeZone property. If the specified value is nil or is a date in the past, the notification is delivered immediately.

因此,处理这种情况是程序员的责任。您可以做的一件事是,将您要设置的日期与当前日期进行比较。如果小于则不要设置。

问题是您必须在设置 fireDate 之前定义本地时区。