Stewart Lynch
Stewart Lynch

Reputation: 995

Adding a reference in CloudKit Record

I am trying to create a record and a set of reference records in cloudkit. I first create a Category and then I add a number of locations records that reference this category. When I create the category, I use a timeStamp for the recordID and try to set that RecordID as the reference for each location record that is added. However, when I do that, I do get the category record and all of the location records created, but the reference field (named Category) is blank. This is what I am doing. What am I missing?

 func createCategoryandLocations() {
        let container = CKContainer.defaultContainer()
        let publicDatabase = container.publicCloudDatabase
        let timestampAsString = String(format: "%f", NSDate.timeIntervalSinceReferenceDate())
        let timestampParts = timestampAsString.componentsSeparatedByString(".")
        let recordID = CKRecordID(recordName: timestampParts[0])
        let categoryRecord = CKRecord(recordType: "Category", recordID: recordID)
        categoryRecord.setObject(category.name, forKey: "CategoryName")
        let CatReference = CKReference(recordID: recordID, action: CKReferenceAction.DeleteSelf)

        publicDatabase.saveRecord(categoryRecord) {
            record, error in
            if error != nil {
                print(error?.localizedDescription)
            } else {
                print("Recorded")
                // Now upload locations for recordID
                print("refID \(CatReference)")
                for location in self.locations {
                    let coordinates = CLLocation(latitude: location.latitude, longitude: location.longitude)
                    let locationRecord = CKRecord(recordType: "Location")
                    locationRecord.setObject(location.address, forKey: "Address")
                    locationRecord.setObject(CatReference, forKey: "Categoy")
                    locationRecord.setObject(location.site,forKey: "Name")
                    locationRecord.setObject(coordinates, forKey: "Coordinates")
                    locationRecord.setObject(location.comment, forKey: "Comment")
                    publicDatabase.saveRecord(locationRecord) {
                        record, error in
                        if error != nil {
                            print(error?.localizedDescription)
                        } else {
                            print("Recorded \(location.site)")
                        }
                    }
                }
            }
        }
    }

Upvotes: 1

Views: 854

Answers (1)

Edwin Vermeer
Edwin Vermeer

Reputation: 13127

Because you set the field "Categoy" instead of "Category". It should be:

locationRecord.setObject(CatReference, forKey: "Category")

Instead of:

locationRecord.setObject(CatReference, forKey: "Categoy")

Upvotes: 1

Related Questions