blobswift-data

How to store variable of type Data in SwiftData


I'm wondering if there is any special way how to store variable of type Data in SwiftData persistent storage. All data in my record are stored fine but Data type is not. I have my model defined like this

@Model
final class Purchase {

    @Attribute(.unique) var purchaseID: String
    var item: String
    var comment: String?
    var documentURL: URL?
    var bookmarkURL: Data?
    var purchaseDate: Date
    var endOfWarranty: Date
    var rating: Double
    .....
}

and then in my code I do storing (updating of already existing record) like this

purchase?.shop = selectedShop
purchase?.item = item
purchase?.comment = comment
purchase?.documentURL = documentURL
purchase?.bookmarkURL = bookmarkURL
purchase?.purchaseDate = date
purchase?.endOfWarranty = Calendar.current.date(byAdding: .month, value: warranty, to: date)!
do {
    try modelContext.save()
} catch let error {
    isError = true
    errMsg = error.localizedDescription
}

purchase.bookmarkURL remains null/nil even if bookmarkURL variable is filled. Thanks for hints.


Solution

  • The solution I have seen for storing Data properties is to say that it should be stored in an external file using @Attribute(.externalStorage)

    @Attribute(.externalStorage) var bookmarkURL: Data?