【问题标题】:How to save an Increment in Swift如何在 Swift 中保存增量
【发布时间】:2018-09-05 08:12:23
【问题描述】:

我正在设计一个摄影师的应用程序。我添加了一个应用程序费率窗口。它工作得很好,但它的增量不起作用。我将它编程为“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()

【问题讨论】:

  • 我无法重现该问题。每次应用程序启动时,运行次数都会增加。
  • 注意:不要打电话给.synchronize()。来自Apple's documentation... “这个方法是不必要的,不应该使用。”
  • @MartinR 看看 UserDefaults() 和 UserDefaults.standard 的区别:stackoverflow.com/questions/40026196/…

标签: ios swift increment


【解决方案1】:

您确定“每次我打开应用程序”确实是在重新启动应用程序吗? (杀死应用程序并再次点击应用程序图标)。如果不是,那么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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 2017-12-05
    • 2017-01-11
    • 2020-04-29
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    相关资源
    最近更新 更多