iosswiftanalyticswatchos-2

Check how many consecutive days a user has used an app


I've already seen other questions asking about how many times the app has been opened. I want to send a local notification when the user uses the app for 31 consecutive days.

Would this be a NSUserDefaults discovery method or would I need to use an analytics API?


Solution

  • Use UserDefault. In appdelegate's didFinishLaunch method check for days count

    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
    }