检查用户连续使用应用的天数

Check how many consecutive days a user has used an app

我已经看到其他问题询问应用程序被打开了多少次。我想在用户使用该应用程序 31 连续 天时发送本地通知。

这是 NSUserDefaults 发现方法还是我需要使用分析 API?

使用UserDefault。在 appdelegate 的 didFinishLaunch 方法中检查天数

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
     
    let kLastUsed = "LastUsedTime"
    let kDaysCount = "DaysCount"
    let currentDateTimeInterval = Int(Date().timeIntervalSinceReferenceDate)
    var storedDaysCount:Int = UserDefaults.standard.integer(forKey: kDaysCount)
    if storedDaysCount >= 31 {
        //show pushNotifications
    }
    else {
        let lastDateTimeInterval = UserDefaults.standard.integer(forKey: kLastUsed)
    
        let diff = currentDateTimeInterval - lastDateTimeInterval
        if diff > 86400 && diff < 172800 {
            //next day. increase day count by one
            storedDaysCount = storedDaysCount + 1
            UserDefaults.standard.set(storedDaysCount, forKey: kDaysCount)
        }
        else if diff > 86400 {
            //not next day. reset counter to 1
            UserDefaults.standard.set(1, forKey: kDaysCount)
        }
        
        UserDefaults.standard.set(currentDateTimeInterval, forKey: kLastUsed)
    }
    
    return true
}

只是扩展了 Hitesh 的精彩回答,使其更适合实时测试。

您不能像在真实设备上那样在模拟器设置中更改日期。如果您在真实设备上更改日期,您可能会遇到一些 Apple 服务器-Xcode 同步问题,并且 Xcode 会要求您再次在开发者门户中注册您的设备。

*使用当前时间在真实设备上进行测试,因为 UserDefaults 需要来自真实设备的日期和存储。

要测试分钟或秒,只需将所有 Ints 更改为 Doubles 并将条件更改为更精细的条件,例如 if storedDaysCount >= 0.0000000015

let kLastUsed = "LastUsedTime"
let kDaysCount = "DaysCount"
let currentDateTimeInterval = Double(Date().timeIntervalSinceReferenceDate)

var storedDaysCount:Double = UserDefaults.standard.double(forKey: kDaysCount)
    if storedDaysCount >= 0.000000000015 {

        print("storedDaysCount = \(storedDaysCount)")