2

I am using in my App cloudKit + Core Data in my App (iOS 13+) (swift).

I cannot figure out how to detect very first run of the app regardless of device to initialize some default data.

There are many posts how to detect first launch of a iOS app on specific device - that's easy. I cannot find solution for detecting the first run of app for specific user or in other words - if in user's iCloud does exist initialized container with specific containerIdentifier.

If user had already used the app on another device before, so during first launch on new device, there will be sync with iCloud and app will use user's data. But if the user has never used the app before I need to initialize some data.

I am searching for clue how to deal with it for hours, cannot find nothing relevant. Any idea?

Thanks for help in advance.

GrLb71
  • 51
  • 6

1 Answers1

0

A bit more information on your cloudkit schema would help, but assuming you are using a publicDB to store information, a unique record will be create for the user when they first take an action that saves data to cloudkit.

So you could check and look at the createDate timestamp of the User object in cloudkit and compare to the current time (a bit clunky, but possible). enter image description here

Example code to fetch the user:

iCloudUserIDAsync { (recordID: CKRecord.ID?, error: NSError?) in
    if let userID = recordID?.recordName {
        self.loggedInUserID = userID

        self.loggedInWithiCloud = true
    } else {
        self.loggedInWithiCloud = false

        print("Fetched iCloudID was nil")
    }
}

Alternatively, and more elegantly, you could write a boolean flag to the user object CloudKit (or locally in CoreData) on first launch. Then on any launch get the entire user object for the logged in iCloud user, you can then initialize it and then act on your Boolean variable from there.

Example code to get the full user and initialize it locally:

    CKContainer.default().publicCloudDatabase.fetch(withRecordID: userRecordID) { (results, error ) in
        if results != nil {
          //now that you have the user, you can perform your checks
            self.currentUser = MyUser(record: results!)
        }
        if let error = error {
            print("couldn't set user reference")
        }
        DispatchQueue.main.async {
            completion(nil)
        }
    }
Steve B
  • 520
  • 4
  • 11