计算两个日期之间的差异。 Swift 1.2

Calculate the difference between two dates. Swift 1.2

我需要一种方法来确定矿石完成 "unknown" 时间后的时间。

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

谢谢

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

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

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

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

注意:您需要在应用启动时请求通知权限。我在这里用 notificationsAllowedsoundsAllowed 简化了这个,它们是我的 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
        }
}