检查用户已连续使用几天的应用程序

时间:2018-07-29 02:22:45

标签: ios swift analytics watch-os-2

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

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

2 个答案:

答案 0 :(得分: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 > 3600 && diff < 7200 {
            //next day. increase day count by one
            storedDaysCount = storedDaysCount + 1
            UserDefaults.standard.set(storedDaysCount, forKey: kDaysCount)
        }
        else if diff > 3600 {
            //not next day. reset counter to 1
            UserDefaults.standard.set(1, forKey: kDaysCount)
        }

        UserDefaults.standard.set(currentDateTimeInterval, forKey: kLastUsed)
    }

    return true
}

答案 1 :(得分:1)

只需扩展Hitesh的出色答案即可使其更适合实时测试。

您无法像在真实设备上那样在模拟器设置中更改日期。而且,如果您在真实设备上更改日期,则可能会遇到一些Apple服务器与Xcode同步的问题,并且Xcode会要求您再次在Developer Portal中注册设备。

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

要测试几分钟或几秒钟,只需将所有Ints更改为Doubles,然后将条件更改为类似 ifstoredDaysCount> = 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)")