Save image to core data

In my swift code I am trying to save a image. Someone gave me this code and its not making sense. I don’t understand the extension files. My core data entity is named Info. I don’t have any attributes. I am getting a runtime error on @nonobjc public class func fetchRequest() → NSFetchRequest stating fetch request is re declared. Other than that no issues. Just want to get the code to work.

import UIKit;import CoreData

class ViewController: UIViewController {

    
      var images:[UIImage] = [] {
          didSet {
              print(images.count)
  //            reload tableView or collectionView
          }
      }
      
      override func viewDidLoad() {
          super.viewDidLoad()
      }
      
      func saveImage(image:UIImage,fileName:String) {
          image.save(to: fileName)
          DataBaseHelper.shareInstance.saveImage(fileName: fileName)
      }
      
      func getImage() {
          let allInfo = DataBaseHelper.shareInstance.fetchInfo()
          for info in allInfo {
              if let name = info.imageName {
                  let image = UIImage(fileName: name)
                  self.images.append(image)
              }
          }
      }

}

class DataBaseHelper {
    
    static let shareInstance = DataBaseHelper()
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    func saveImage(fileName: String) {
        let imageInstance = Info(context: context)
        imageInstance.imageName = fileName
        
        do {
            try context.save()
            print("Image name is saved")
        } catch {
            print(error.localizedDescription)
        }
    }
    
    func fetchInfo() -> [Info] {
        var fetchingImage = [Info]()
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Info")
        
        do {
            fetchingImage = try context.fetch(fetchRequest) as! [Info]
        } catch {
            print("Error while fetching the image")
        }
        
        return fetchingImage
    }
}
extension UIImage {
    
    func save(to fileName:String)  {
        let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!;
        let fileURL = documentsUrl.appendingPathComponent(fileName)
        if let imageData = self.jpegData(compressionQuality: 1) {
            try? imageData.write(to: fileURL, options: .atomic)
        }
    }
    
    
    convenience init(fileName: String) {
        var data = Data()
        let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!;
        let fileURL = documentsUrl.appendingPathComponent(fileName)
        do {
            let imageData = try Data(contentsOf: fileURL)
            data = imageData
        } catch {
            print(error.localizedDescription)
        }
        self.init(data: data)!
    }
    
}

extension Info {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Info> {
        return NSFetchRequest<Info>(entityName: "Info")
    }

    @NSManaged public var imageName: String?

}

extension Info : Identifiable {

    
}

That’s because NSManagedObject already has a fetchRequest() method:

https://developer.apple.com/documentation/coredata/nsmanagedobject/1640605-fetchrequest

I would recommend going through a Core Data tutorial, and before that a Swift tutorial on extensions. A good rule of thumb is if something is confusing, make it clear, it will keep your code right.

what specifically can i do to fix this code. I dont know why fetch request is repeated twice.

It sounds like maybe reviewing the fundamentals would help, there’s plenty on the RW website:

I would also not recommend storing images using Core Data, that’s not what it was meant to do. It was meant to abstract and store data models. More efficient mechanisms for binary data or whole files, such as FileManager/iCloud Drive.

Steps to Save Images in CoreData

Save the image in core data.
To fetch the saved image from the core data, use the following code.
Convert the imageData to UIImage to display it to the user.
Save array of images to core data.
Fetch array of images from core data.
Convert the array of imageData to UIImage as.

This may help you,
Rachel Gomez