Reputation: 1
I want to let users of the app create posts for a feed but I want to store post images separate to speed up load times. Is it possible to store images in one record and then fetch them along with the post that they belong to at the same time that I fetch the post? If so how would I implement this in SwiftUI?
I have already figured out how to save/fetch post just not images.
Upvotes: 0
Views: 113
Reputation: 14070
Yes, you can certainly do this. I'm going to assume your recordType
is a Post
that has the content for an item in your feed.
I can think of two options. Regardless of what approach you take, you should be storing your images as CKAsset
on CloudKit.
== Option 1 ==
You can have a field on a Post
that is of type Asset List
and load it up with CKAsset
records which will be your images. When you access each CKAsset
, it gets downloaded after you have the original Post
record. This is probably the cleanest approach.
== Option 2 ==
Make another recordType
called Image
and it could have a field of type Reference
(a CKReference
) back to a Post
. So as each Image
is created, it gets assigned a Post
and points to it.
When you query for your Post
records, you also query for all the Image
records that are connected to the Post
. This could be done like this:
let query = CKQuery(recordType: "Image", predicate: NSPredicate(format: "post = %@", CKRecord.Reference(recordID: CKRecord.ID(recordName: yourPostRecordName), action: .deleteSelf)))
let operation = CKQueryOperation(query: query)
var images = [CKRecord]()
operation.recordFetchedBlock = { record in
//Load up all the images
images.append(record)
}
operation.queryCompletionBlock = { cursor, error in
//All the image records have been downloaded, or there was an error
}
yourContainerDatabase.add(operation)
Upvotes: 0