caneraltuner
caneraltuner

Reputation: 284

How to save an Increment in Swift

I'm designing an app of a photographer. I added an app rate window. It works well, but its increment isn't working.I programmed it for "After 3 open the window". Every time I open the app, the console outputs "run count = 0". That is my problem and I don't know to solve it.

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()

Upvotes: 2

Views: 847

Answers (1)

TheTiger
TheTiger

Reputation: 13354

Are you sure by "Every time I open the app" you are actually relaunching the app? (Killing the app and tap the app icon again). If not then didFinishLaunchingWithOptions: will not call and you will have to handle this in applicationDidBecomeActive: instead.

Apart from this there are two more suggestions while using UserDefaults

  1. Don't use value(forKey:, Use integer(forKey: instead while working with integer value.
  2. And don't call .synchronize().

Below code is working fine:

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
}

Upvotes: 2

Related Questions