计算从上次应用程序终止到下一次启动的时间段(以秒为单位)

Calculating the period of time from last app termination to the next launch in seconds

我需要知道从应用终止到应用再次启动之间经过了多少时间。我猜你必须在 appIsTerminated 时通过将它保存在 appDelegate 中来存储 startDate。然后,您必须在 appDidLaunch 和 appDelegate 中访问该值,然后计算这些时间之间的差异。我需要以秒为单位的差异,我想在 viewController 中使用差异。我如何在 swift 3、Xcode 8 中执行此操作?

Dateclass有一个timeIntervalSince函数:

date2.timeIntervalSince(date1)

返回的TimeInterval是从date1date2的秒数。

如果你想在你的视图控制器中使用它,你可以将它保存在某个地方,比如 UserDefaults 并从那里访问它。

是的,你是对的,这是最简单的解决方案。

public func applicationDidFinishLaunching(_ application: UIApplication){

    UserDefaults.standard.set(Date(), forKey: "latestLaunchDate")
    // your code
    return true
}


public func applicationWillTerminate(_ application: UIApplication) {
     UserDefaults.standard.set(Date(), forKey: "latestTerminationDate")
     //just to ensure that it is saved
     UserDefaults.standard.syncronize()
}

然后在你的 ViewController

class YourViewController: UIViewController {

    func method() {
         if let launchDate = UserDefaults.standard.object(forKey:  "latestLaunchDate") as? Date,
            let terminationDate = UserDefaults.standard.object(forKey: "latestTerminationDate") as? Date
         {
             // your duration
             let terminationDuration = launchDate.timeIntervalSince(terminationDate)
         }
    }
}

因此,在上面的示例中,只有在两个日期(启动和终止都已设置)的情况下,您才会到达 if 正文。 更好的方法是为此目的定义一些 全局常量,这样你就不会在某处输入字符串错误。