我需要将从Internet下载的图像保存到CoreData。
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photos.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionPhotoCell", for: indexPath) as! PhotoCollectionCell
let photo = photos[(indexPath as NSIndexPath).row]
if let getImage = photo.getImage() {
cell.photoImageView.image = getImage
}
else {
// Photo Placeholder
cell.photoImageView.image = UIImage(named: "imgPlaceholder.png")
// Activity Indicator
cell.activityIndicator.isHidden = false
cell.activityIndicator.startAnimating()
FlickrClient().imageData(photo) {
(imageData, error) in
guard error == nil else {
return
}
DispatchQueue.main.async {
cell.activityIndicator.isHidden = true
cell.activityIndicator.stopAnimating()
cell.photoImageView.image = UIImage(data: imageData!)
}
}
}
cell.photoImageView.alpha = 1.0
return cell
}
更新:
在CoreData中,实体是Photos,Attribute是imageData。查看下面的代码,managedObjectContext.save()
如何将下载的图像(在collectionView中)保存到CoreData?我还是很困惑。
let photos = NSEntityDescription.insertNewObjectForEntityForName("Photo", inManagedObjectContext: self.managedObjectContext!) as Photo
do {
try managedObjectContext.save()
} catch {
fatalError("Failure to save")
}
答案 0 :(得分:0)
您可以通过以下方式从AppDelegate获取托管对象上下文:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = appDelegate.persistentContainer.viewContext