How to save and load text & images in DocumentsDirectory

Here's basic code of my ToDo App: Data:

struct ToDo: Codable {
    var title: String
    var isCompleted: Bool
    var dateCreated: Date
    var notes:  String 
    
    static let DocumentsDirectory =
    FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    
    static let ArchiveURL = DocumentsDirectory.appendingPathComponent("todos") .appendingPathExtension("plist")

    static func loadToDos() -> [ToDo]? {
        guard let codedToDos = try? Data(contentsOf: ArchiveURL) else {return nil}

        let propertyListDecoder = PropertyListDecoder()
        return try? propertyListDecoder.decode(Array<ToDo>.self, from: codedToDos)
    }

    static func saveToDos(_ todos: [ToDo]) {
        let propertyListEncoder = PropertyListEncoder()
        let codedToDos = try? propertyListEncoder.encode(todos)
        try? codedToDos?.write(to: ArchiveURL,
          options: .noFileProtection)
    }

   I have a tableViewController to display the data's detail, there's a noteTextView (textView) for editing/adding the todo.note. There's a Camera Button allows user to insert the images into (textView) todo.note using NSTextAttachment():

internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        let attachment = NSTextAttachment()
        let image = info[.originalImage] as! UIImage
        attachment.image = image

        //Resize Photo to fit in noteTextView: calculate new size so want a litter space on the right of image
        let newImageWidth = (noteTextView.bounds.size.width - 20)
        let scale = newImageWidth/image.size.width
        let newImageHeight = image.size.height * scale
        attachment.bounds = CGRect.init(x: 0, y: 0, width: newImageWidth, height: newImageHeight)

        //attributedString=NSTextAttachment() 
        let imageString = NSAttributedString(attachment: attachment)

        // add this attributed string to the cusor position
        noteTextView.textStorage.insert(imageString, at: noteTextView.selectedRange.location)
        picker.dismiss(animated: true, completion: nil)
    }

The code working well. Now, how do I save it (with images) to DocumentsDirectory and how do I load it back? I can save/load without images.

Thanks.

Answered by jimmychang26 in 717901022

Done

Does anyone have any suggestions?

Accepted Answer

Done

I am facing the same problem! How did you end saving the images? Thanks!

How to save and load text &amp; images in DocumentsDirectory
 
 
Q