如何在Swift中保存增量

时间:2018-09-05 08:12:24

标签: ios swift increment

我正在设计摄影师的应用程序。我添加了一个应用费率窗口。它工作正常,但其增量不起作用。我将其编程为“ 3打开窗口后”。每次我打开应用程序时,控制台都会输出“运行计数= 0”。 那是我的问题,我不知道要解决。

let runIncrementerSetting = "numberOfRuns"  // UserDefauls dictionary key where we store number of runs
let minimumRunCount = 3                     // Minimum number of runs that we should have until we ask for review

func incrementAppRuns() {                   // counter for number of runs for the app. You can call this from App Delegate
    let usD = UserDefaults()
    let runs = getRunCounts() + 1
    usD.setValuesForKeys([runIncrementerSetting: runs])
    usD.synchronize()

}

func getRunCounts () -> Int {               // Reads number of runs from UserDefaults and returns it.
    let usD = UserDefaults()
    let savedRuns = usD.value(forKey: runIncrementerSetting)
    var runs = 0
    if (savedRuns != nil) {            
       runs = savedRuns as! Int
    }
    print("Run Counts are \(runs)")
    return runs        
}

func showReview() {        
    let runs = getRunCounts()
    print("Show Review")
    if (runs > minimumRunCount) {
        if #available(iOS 11.0, *) {
            print("Review Requested")
            SKStoreReviewController.requestReview()           
        } else {
            // Fallback on earlier versions
        }
    } else {        
        print("Runs are not enough to request review!")        
    } 
}

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    incrementAppRuns()
    return true
}
showReview()

1 个答案:

答案 0 :(得分:2)

通过“每次我打开应用程序” 确定您确实要重新启动该应用程序吗? (杀死应用程序,然后再次点击应用程序图标)。如果不是,那么didFinishLaunchingWithOptions:将不会呼叫,您将不得不在applicationDidBecomeActive:中处理。

除此之外,在使用UserDefaults时还有另外两个建议

  1. 在使用整数值时,请勿使用value(forKey:,而应使用integer(forKey:
  2. 也不要拨打.synchronize()

以下代码运行正常:

func incrementAppRuns() {
    let usD = UserDefaults.standard
    let runs = getRunCounts() + 1
    usD.set(runs, forKey: runIncrementerSetting)
}

func getRunCounts() -> Int {
    let usD = UserDefaults.standard
    let runs = usD.integer(forKey: runIncrementerSetting)
    print("Run Counts are \(runs)")
    return runs
}