【问题标题】:Calculate the difference between two dates. Swift 1.2计算两个日期之间的差异。斯威夫特 1.2
【发布时间】:2015-05-10 06:53:13
【问题描述】:

我需要一种方法来确定在完成矿石的“未知”时间之后的时间。

启动计时器后,它需要计算何时发送本地通知。 我需要一种方法,以便应用程序可以完全关闭并仍然通知他们。

谢谢

这是我在实现“notificationsAllowed”代码时遇到的错误。

【问题讨论】:

    标签: swift nsdate uilocalnotification nscalendar


    【解决方案1】:

    要计算结束时间,您可以使用

    timerEndTime = NSDate(timeIntervalSinceNow:NSTimeInterval(oreWanted * 11))
    

    所以你得到一个NSDate 对象。现在您可以在计算出的时间触发UILocalNotification:

    注意:您需要在应用启动时请求通知权限。我在这里用notificationsAllowed 和soundsAllowed 简化了这一点,它们是我的AppDelegate 中的布尔变量。

    let appDelegate = UIApplication.sharedApplication.delegate as! AppDelegate
    
    if appDelegate.notificationsAllowed {
        let notification = UILocalNotification()
        notification.fireDate = timerEndTime
        notification.timeZone = NSTimeZone.defaultTimeZone()
        notification.alertBody = "Notification body text"
        notification.alertTitle = "Notification alert title"
    
        if appDelegate.soundsAllowed {
            notification.soundName = UILocalNotificationDefaultSoundName
        }
    
        UIApplication.sharedApplication().scheduleLocalNotification(notification)
    }
    

    编辑

    在 AppDelegate 中为应用注册通知:

    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        var window: UIWindow?
    
        var notificationsAllowed = false
        var notificationSoundAllowed = false
    
    
        func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
            let notificationSettings = UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert, categories: nil)
            UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
    
            return true
        }
    
        func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
            if notificationSettings.types & UIUserNotificationType.Alert != nil {
                self.notificationsAllowed = true
            }
    
            if notificationSettings.types & UIUserNotificationType.Sound != nil {
                self.notificationSoundAllowed = true
            }
    }
    

    【讨论】:

    • 很高兴为您提供帮助。如果这是解决方案,请通过单击空心复选标记将答案标记为正确。谢谢。
    • 您知道一种方法,即使用户单击主页按钮,计时器也会继续运行?
    • 这样用户可以看到还剩多少时间
    • 将计算出的结束时间写入NSUserDefaults,并在用户下次激活应用时读取。因此无需让应用程序在后台运行。
    • 但在应用关闭时需要继续倒计时。
    猜你喜欢
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 2021-11-25
    • 2011-08-01
    相关资源
    最近更新 更多