Search code examples
swiftmapkitcloudkit

Fetch CloudKit records from current iCloud user


I want to fetch all of the location records from a user that is currently logged in.

This creates the location record on CloudKit:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations.last!
    let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
    addCrumbPoint(center)
    let locationRecord = CKRecord(recordType: "location")
    locationRecord["location"] = location
    let publicData = CKContainer.defaultContainer().publicCloudDatabase
    publicData.saveRecord(locationRecord) { record, error in
    }
}

But how would I go about pulling out the location records for only the currently logged in user?

I want to use this to create a breadcrumb of previous journeys on a map but just getting it to print a list would be a great start!

Here is my code so far:

 func getLocationAsync(complete: (instance: CKRecordID?, error: NSError?) -> ()) {
    let container = CKRecordID(recordName: "Location")
    publicDB.fetchRecordWithID(location) { fetchedLocation, error in
        if error != nil {
            print(error!.localizedDescription)
            complete(instance: nil, error: error)
        } else {
            print("fetched Location \(recordID?.recordName)")
            complete(instance: recordID, error: nil)
        }
    }
}

Solution

  • If your goal is to save the breadcrumbs locations of an user and not sharing it to other users, then use the private database. Like that you can retrieve all the location records of the user.

    If you want to use the public DB, then add an entry of type CKReference to the Location record pointing to the user record. So that you can use a predicate based on the user recordID