Search code examples
swiftswiftdata

Storing multiple images in swift data


I am currently working on a project that needs to allow users to store multiple images in swift data! I was wondering if anyone knew how to do this. below is my current model

import Foundation
import SwiftData

@Model
class SwiftDataModel {
    // Session Data
    var record_type: WorkRecordType
    var amount: Int
    var nameOfSession: String
    var date: Date
    var canvas: Data
    var taps: Int
    @Attribute(.externalStorage) var photo: Data?
    // Doc Scan Data
   
    // Event Data
    var subject_type: EventType
    var name_of_event: String
    var event_date: Date
    var is_notified: Bool
    
    init(amount: Int = 0, nameOfSession: String = "", Date: Date = .now, /*canvas: Data = Data(),*/ record_type: WorkRecordType = .dont_record, taps: Int = 0, name_of_event: String = "", event_date: Date = .now, subject_type: EventType = .other, is_notified: Bool = false) {
        // Session Data
        self.amount = amount
        self.nameOfSession = nameOfSession
        self.date = Date
        self.canvas = Data()
        self.record_type = record_type
        self.taps = taps
        // Event Data
        self.name_of_event = nameOfSession
        self.event_date = Date
        self.subject_type = subject_type
        self.is_notified = is_notified
        //Doc Scan Data
        
    }
}

I know how to store one image in swift data but I dont know how to store an array of images in swift data.


Solution

  • You can create a new model that holds the image data:

    @Model class Photo {
        var id: UUID //optionally add some other fields if needed
        @Attribute(.externalStorage) var photo: Data
        init(photo: Data) {
            self.id = UUID()
            self.photo = photo
        }
    }
    

    And in SwiftDataModel you can add a [Photo] property which will create a one to many relation between the 2 models.

    Using @Relationship(deleteRule: .cascade) here will allow you to automatically remove the photos when deleting their parent.

    @Model
    class SwiftDataModel {
        @Relationship(deleteRule: .cascade) var photos: [Photo]
        ...
    }
    

    Note: Saving an array of Data in SwiftDataModel works but gives you the following warnings:

    CoreData: debug: PostSaveMaintenance: fileSize 28234392 greater than prune threshold CoreData: annotation: PostSaveMaintenance: wal_checkpoint(TRUNCATE)