Favorite Button using CoreData

Asked by At

I need to add only one entry to the database. If the database is empty then for some reason nothing is added. If the database had records then added several of the same records because of the cycle I guess. Here is my code:

import UIKit
import AVFoundation
import CoreData

class PlayerViewController: UIViewController, VLCMediaPlayerDelegate {
@IBOutlet var favoriteBarButton: UIBarButtonItem!

@IBAction func addFavorites(_ sender: UIBarButtonItem) { 
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "MarkersModel", in: context)

let request: NSFetchRequest<MarkersModel> = MarkersModel.fetchRequest()
request.returnsObjectsAsFaults = false
request.includesPropertyValues = false
    do {                    let result = try context.fetch(request)

                                            for (i, s) in result.enumerated() {
                                                // Can simply use 'sender' here, no need to index into senderArray.
                                                if s.nameCam == self.webcamTitle! {
                                                    let value = result[i]
                                                    context.delete(value)
                                                    self.favoriteBarButton?.tintColor = .red
                                                    //do {
                                                    try context.save()
                                                    //}
                                                }
                                                if s.nameCam != self.webcamTitle!
                                                {
                                                    let newFavoriteCamera = NSManagedObject(entity: entity!, insertInto: context)
                                                    newFavoriteCamera.setValue(self.webcamTitle, forKey: "nameCam")
                                                    newFavoriteCamera.setValue(self.webcamURL, forKey: "urlCam")
                                                    self.favoriteBarButton?.tintColor = .green
                                                    //do {

                                                    //let value = result[i]
                                                    context.insert(newFavoriteCamera)
                                                    try context.save()
                                                    //}
                                                }
                                            }
}

enter image description here

2 Answers

0
Paul Lochte On Best Solutions

I did what I wanted to do. Here is my code for anyone interested. It works =)

@IBAction func addFavorites(_ sender: UIBarButtonItem) {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: "MarkersModel", in: context)
    let request: NSFetchRequest<MarkersModel> = MarkersModel.fetchRequest()
    request.returnsObjectsAsFaults = false
    var array: [String] = []

    do {
        let result = try context.fetch(request)
        for data in result {
            array.append(data.nameCam!)
            print(array)
        }
    }catch {
        print(error)}
    do {
        let newFavoriteCamera = NSManagedObject(entity: entity!, insertInto: context)
        newFavoriteCamera.setValue(self.webcamTitle, forKey: "nameCam")
        newFavoriteCamera.setValue(self.webcamURL, forKey: "urlCam")
        let result = try context.fetch(request)

        if array.contains(self.webcamTitle) {
            for data in result {
                if data.nameCam == self.webcamTitle {
                    favoriteBarButton?.tintColor = .red
                    print("YES")
                    context.delete(data)
                    try context.save()
                }
            }
        } else{
            print("NO")
            self.favoriteBarButton?.tintColor = .green
            try context.save()
            print(array)
        }
    } catch {
        print(error)}
}


func RequestFromDB() {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: "MarkersModel", in: context)

    let request: NSFetchRequest<MarkersModel> = MarkersModel.fetchRequest()
    request.returnsObjectsAsFaults = false

    var array1: [String] = []

    do {
        let result = try context.fetch(request)
        for data in result {
            array1.append(data.nameCam!)
        }
    } catch {
        print(error)}

    print(array1)
    //let u = "Maine, Caribouw"
    if array1.contains(self.webcamTitle) {
        print("YES")
        self.favoriteBarButton?.tintColor = .green
    } else{
        print("NO")
        self.favoriteBarButton?.tintColor = .red
    }


}
override func viewDidLoad() {
    super.viewDidLoad()
    RequestFromDB()

}

0
B2Fq On

Load:

var DataItem = [EntityName] ()

if (DataItem.value(forKeyPath: "favorite") as? Bool)! == true {
   FavoriteButton.setImage(#imageLiteral(resourceName: "Star_white_selected"), for: .normal)
} else {
   FavoriteButton.setImage(#imageLiteral(resourceName: "Star_white_unselected"), for: .normal)
}

Button action:

if FavoriteButton.currentImage == UIImage(named: "Star_white_selected") {
   FavoriteButton.setImage(#imageLiteral(resourceName: "Star_white_unselected"), for: .normal)
   updateData(add: false)
} else if FavoriteButton.currentImage == UIImage(named: "Star_white_unselected") {
   FavoriteButton.setImage(#imageLiteral(resourceName: "Star_white_selected"), for: .normal)
   updateData(add: true)
}

func updateData(add: Bool) {
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
    let managedContext = appDelegate.persistentContainer.viewContext

    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Name")
    fetchRequest.predicate = NSPredicate(format: "nameCam = %@", self.webcamTitle)

    do {
        let test = try managedContext.fetch(fetchRequest)
        let objectUpdate = test[0]
        objectUpdate.setValue(add, forKey: "favorite")
        appDelegate.saveContext()
    } catch {
        print(error)
    }
}