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 {
}