// // MainViewController.swift // ApartaApp // // Created by Berkay Sarıpınar on 17.10.2023. // import UIKit import CoreData import SwiftQRScanner class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate { var fetchedResultsController: NSFetchedResultsController! @IBOutlet weak var tableView: UITableView! let addButton: UIButton = { let button = UIButton() button.backgroundColor = .red button.layer.cornerRadius = 25 button.layer.masksToBounds = true button.setImage(UIImage(systemName: "plus"), for: .normal) button.tintColor = .white button.translatesAutoresizingMaskIntoConstraints = false return button }() override func viewDidLoad() { super.viewDidLoad() // addTestData() tableView.delegate = self tableView.dataSource = self // Butonu ekle view.addSubview(addButton) // Butonun pozisyonunu ve boyutunu ayarla NSLayoutConstraint.activate([ addButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -25), addButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -50), addButton.widthAnchor.constraint(equalToConstant: 50), addButton.heightAnchor.constraint(equalToConstant: 50) ]) // "+" işaretini butonun ortasına yerleştirelim if let titleSize = addButton.titleLabel?.frame.size { let imageInset = (addButton.frame.size.height - titleSize.height) / 2 //addButton.titleEdgeInsets = UIEdgeInsets(top: imageInset, left: -imageInset, bottom: -imageInset, right: imageInset) } // Butona tıklandığında çağrılacak fonksiyonu belirle addButton.addTarget(self, action: #selector(scanQRCode), for: .touchUpInside) // Core Data için fetchedResultsController'ı ayarla setupFetchedResultsController() fetchDevices() } func setupFetchedResultsController() { let fetchRequest: NSFetchRequest = DeviceEntity.fetchRequest() let sortDescriptor = NSSortDescriptor(key: "name", ascending: true) fetchRequest.sortDescriptors = [sortDescriptor] fetchedResultsController = NSFetchedResultsController( fetchRequest: fetchRequest, managedObjectContext: CoreDataStack.shared.context, sectionNameKeyPath: nil, cacheName: nil ) fetchedResultsController.delegate = self do { try fetchedResultsController.performFetch() } catch { print("Error fetching devices: \(error)") } } func fetchDevices() { do { try fetchedResultsController.performFetch() tableView.reloadData() } catch { print("Error fetching devices: \(error)") } } @objc func addButtonTapped() { // Buraya yeni cihaz ekleme ekranına geçiş kodunu ekleyebiliriz } // MARK: - TableView DataSource ve Delegate Metotları func numberOfSections(in tableView: UITableView) -> Int { return fetchedResultsController.sections?.count ?? 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return fetchedResultsController.sections?[section].numberOfObjects ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "deviceCell", for: indexPath) as! DeviceCell configureCell(cell, at: indexPath) return cell } func configureCell(_ cell: DeviceCell, at indexPath: IndexPath) { let device = fetchedResultsController.object(at: indexPath) cell.deviceNameLabel.text = device.name cell.deviceIDLabel.text = device.id } // MARK: - NSFetchedResultsControllerDelegate Metotları func controllerWillChangeContent(_ controller: NSFetchedResultsController) { tableView.beginUpdates() } func controllerDidChangeContent(_ controller: NSFetchedResultsController) { tableView.endUpdates() } func controller(_ controller: NSFetchedResultsController, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { let indexSet = IndexSet(integer: sectionIndex) switch type { case .insert: tableView.insertSections(indexSet, with: .fade) case .delete: tableView.deleteSections(indexSet, with: .fade) default: break } } func controller(_ controller: NSFetchedResultsController, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: tableView.insertRows(at: [newIndexPath!], with: .fade) case .delete: tableView.deleteRows(at: [indexPath!], with: .fade) case .update: if let cell = tableView.cellForRow(at: indexPath!) as? DeviceCell { configureCell(cell, at: indexPath!) } case .move: tableView.moveRow(at: indexPath!, to: newIndexPath!) } } //MARK: QR CODE SCANNER @objc func scanQRCode(_ sender: Any) { // QRCode scanner without Camera switch and Torch let scanner = QRCodeScannerController() //QRCode with Camera switch and Torch /*let scanner = QRCodeScannerController(cameraImage: UIImage(named: "camera"), cancelImage: UIImage(named: "cancel"), flashOnImage: UIImage(named: "flash-on"), flashOffImage: UIImage(named: "flash-off"))*/ scanner.delegate = self self.present(scanner, animated: true, completion: nil) let storyboard = UIStoryboard(name: "Main", bundle: nil) let addDeviceViewController = storyboard.instantiateViewController(withIdentifier: "AddDeviceViewController") as! AddDeviceViewController } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* func addTestData() { let device1 = DeviceEntity(context: CoreDataStack.shared.context) device1.name = "Cihaz 1" device1.id = "AABB000001" let device2 = DeviceEntity(context: CoreDataStack.shared.context) device2.name = "Cihaz 2" device2.id = "AABB000002" // Diğer cihazlar... CoreDataStack.shared.saveContext() }*/ // Test verileri CoreData func processQRCode(_ qrCode: String) { // QR kodunun uygun formatta olup olmadığını kontrol et guard qrCode.hasPrefix("www.abc.com?id=") else { // Hatalı format, kullanıcıya uyarı ver veya işlemi iptal et // Örneğin: print("Hatalı QR kod formatı") return } // Uygun formatta ise id kısmını çek let idString = qrCode.replacingOccurrences(of: "www.abc.com?id=", with: "") // Şimdi bu id'yi kullanarak yeni cihaz ekleme ekranına yönlendir // Ekranı modally açabilir veya Navigation Controller kullanarak push yapabilirsin let addDeviceViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "AddDeviceViewController") as! AddDeviceViewController // İlgili verileri yeni ekranın view controller'ına iletebilirsin addDeviceViewController.qrCodeID = idString // Ekranı göster performSegue(withIdentifier: "addDeviceVC", sender: nil) } } extension MainViewController: QRScannerCodeDelegate { func qrScannerDidFail(_ controller: UIViewController, error: SwiftQRScanner.QRCodeError) { } func qrScanner(_ controller: UIViewController, scanDidComplete result: String) { print("result:\(result)") processQRCode(result) } func qrScannerDidFail(_ controller: UIViewController, error: String) { print("error:\(error)") } func qrScannerDidCancel(_ controller: UIViewController) { print("SwiftQRScanner did cancel") } }