首页 > 解决方案 > 检查用户连续使用应用程序的天数

问题描述

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

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

标签: iosswiftanalyticswatchos-2

解决方案


使用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
}

推荐阅读