繁体   English   中英

Swift:将照片保存到CoreData

[英]Swift: Saving photos to CoreData

我需要将从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,属性为imageData。 查看下面的代码, managedObjectContext.save()如何将下载的图像(在collectionView中)保存到CoreData? 我还是很困惑。

let photos = NSEntityDescription.insertNewObjectForEntityForName("Photo", inManagedObjectContext: self.managedObjectContext!) as Photo
                do {
                    try managedObjectContext.save()
                } catch {
                    fatalError("Failure to save")
                }

您可以通过以下方式从AppDelegate获取托管对象上下文:

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = appDelegate.persistentContainer.viewContext

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM