Я устанавливаю БД с использованием Core Data, где пользователь может сохранять изображения, эти изображения хранятся в виде пути, у меня есть представление, где я хочу загрузить эти изображения, используя мою ячейку, но изображения не загружаются. Я новичок в этом, у меня есть поиск тонны, но я не могу найти ответ, почему это произошло, пожалуйста, совет.
Мой первоначальный способ попробовать это - установить папку с изображениями внутри моего проекта, и эти картинки фактически загрузятся, но когда я попытался использовать подход URL, они не загрузятся.
Просмотр контроллера
import UIKit
import CoreData
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
let appDelegate = UIApplication.shared.delegate as! AppDelegate
// let array: [String] = ["1","2","3","4","5","6"]
var array: [Image] = []
override func viewDidLoad() {
super.viewDidLoad()
let numberOfColumns: CGFloat = 2
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
let horizontalSpacing = flowLayout.scrollDirection == .vertical ? flowLayout.minimumInteritemSpacing : flowLayout.minimumLineSpacing
let cellWidth = (collectionView.frame.width - max(0, numberOfColumns - 1)*horizontalSpacing)/numberOfColumns
flowLayout.itemSize = CGSize(width: cellWidth, height: cellWidth)
collectionView.collectionViewLayout = flowLayout
}
fetchData()
print("did load")
}
override func viewWillAppear(_ animated: Bool) {
print("WILL APPER")
collectionView.reloadData()
}
// func fetchData() {
// print("data fetch")
// let appDelegate = UIApplication.shared.delegate as! AppDelegate
// let container = appDelegate.persistentContainer
// let context = container.viewContext
// let fetchRequest = NSFetchRequest<Image>(entityName: "Image")
// fetchRequest.returnsObjectsAsFaults = false
//
// do {
// let results = try context.fetch(fetchRequest)
// array = results as [Image]
// } catch let error as NSError {
// print("Could not fetch \(error), \(error.userInfo)")
// }
// }
func fetchData() {
// Setup fetch data
let container = appDelegate.persistentContainer
let context = container.viewContext
let fetchRequest = NSFetchRequest<Image>(entityName: "Image")
do {
// Retrieve array of all images entities in core data
let images = try context.fetch(fetchRequest)
print("COUNT IS ",images.count)
// For each image entity get the imageData from filepath and assign it to image view
for image in images {
array.append(image)
}
} catch {
print("entered catch for image fetch request")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Number of views
// How many items we want, the same as the amout of data we want to display
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print("array count")
print(array.count)
return array.count
}
// Populate the views with the images
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ImageCellController
let imageURL = URL(fileURLWithPath: array[indexPath.row].fullPath!)
print(array[indexPath.row].fullPath)
let image = UIImage(contentsOfFile: imageURL.path)
cell.imageViewCell.image = image
// print(array[indexPath.row])
// cell.imageViewCell.image = UIImage(named: array[indexPath.row] + ".JPG")
// return cell
return cell
}
}
Контроллер ячейки изображения
class ImageCellController: UICollectionViewCell {
@IBOutlet weak var imageViewCell: UIImageView!
}
Кнопки просмотра контроллера
class ButtonsViewController: UIViewController {
@IBOutlet weak var uploadButtn: UIButton!
let imagePicker = UIImagePickerController()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var managedObjectContext: NSManagedObjectContext? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func uploadAction(_ sender: Any) {
let myPickerController = UIImagePickerController()
myPickerController.delegate = self
myPickerController.sourceType = .photoLibrary
present(myPickerController, animated: true, completion: nil)
}
}
extension ButtonsViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
// Get the access to shared instance of the file manager
let fileManager = FileManager.default
// Get the URL for the users home directory
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
print("Documents url: ", documentsURL)
//Get the document url as a string
let documentPath = documentsURL.path
print("Document path is ", documentPath)
let diceRoll = Int(arc4random_uniform(50) + 1)
// Create a filePath URL by appending final path component (name of img)
let filePath = documentsURL.appendingPathComponent("uploadedImage\(String(diceRoll)).png")
print("File path is: ", filePath)
do {
if let pngImageData = UIImagePNGRepresentation(pickedImage) {
try pngImageData.write(to: filePath, options: .atomic)
}
} catch {
}
// Save filepath to CoreData
let container = appDelegate.persistentContainer
let context = container.viewContext
let entity = Image(context: context)
entity.fullPath = filePath.path
appDelegate.saveContext()
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}