【问题标题】:save image to binary data of a ordered index将图像保存为有序索引的二进制数据
【发布时间】:2020-05-22 00:03:28
【问题描述】:

我下面的快速代码试图附加图片中的图像并将其保存到核心数据中。核心数据属性位于下图中。当用户在文本字段中输入 3 时,应显示保存到核心数据中的图像,因为这是索引中的顺序。 2 图像在构建时保存,因此新图像应从索引上的 3 开始。

import UIKit
 import CoreData
   class ViewController: UIViewController,UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

  var imagePicker: UIImagePickerController!

@IBOutlet var enterT : UITextField!
@IBOutlet var pic : UIImageView!
lazy var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

override func viewDidLoad() {
    super.viewDidLoad()

    enterT.delegate = self

    pic.backgroundColor = .cyan
    populateData()
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    guard let text = (textField.text as? NSString)?.replacingCharacters(in: range, with: string), let index = Int(text) else { //here....
        // display an alert about invalid text
        return true
    }
    loadImage(at: index - 1 )
    return true
}




func loadImage(at index : Int) {
    let fetchRequest = NSFetchRequest<Users>(entityName: "Users")
    fetchRequest.predicate = NSPredicate(format: "idx == %d", Int32(index))
    do {
        if let user = try context.fetch(fetchRequest).first {
            pic.image = UIImage(data: user.image!)
        } else {
            pic.image = nil
        }
    } catch {
        print("Could not fetch \(error) ")
    }
}

@IBAction func add(){
      imagePicker =  UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .photoLibrary
    present(imagePicker, animated: true, completion: nil)

}
@IBAction func append(){

}

func populateData()
{
    let item = Users(context: context)
    let vex = UIImage(named: "on.jpg")!.pngData()
    item.image = vex
    item.idx = 0

    let item2 = Users(context: context)
    let vex2 = UIImage(named: "house.jpg")!.pngData()
    item2.image = vex2
    item2.idx = 1

    print("Storing Data..")
    do {
        try context.save()
    } catch {
        print("Storing data Failed", error)
    }
}


func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    // The info dictionary may contain multiple representations of the image. You want to use the original.
    guard let selectedImage = info[.originalImage] as? UIImage else {
        fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
    }

    // Set photoImageView to display the selected image.

    pic.image = selectedImage

    // Dismiss the picker.
    dismiss(animated: true, completion: nil)
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
    if let error = error {
        // we got back an error!
        let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    } else {
        let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    }
}
 }

【问题讨论】:

  • 请检查此项以保存并从 coredata 获取图像:- youtube.com/watch?v=6XQ3735PhiQ
  • @YogeshPatel 我认为您的视频没有核心数据索引或至少如何附加到该索引。

标签: swift core-data indexing append binary-data


【解决方案1】:

populateData方法,里面有创建记录、给属性赋值和保存上下文的代码。

如果要添加多个图像,则必须计算下一个可用索引。索引通常是已保存项目的数量。如果您在索引01 处有两个预定义图像,则下一个可用索引是2

要动态获取已保存记录的数量,请创建获取请求并在上下文中调用 count(for:

let fetchRequest = NSFetchRequest<Users>(entityName: "Users")
let nextAvailableIndex = try context.count(for: fetchRequest)

【讨论】:

  • 我把这段代码放在哪里?我试着把它放在 func append 中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-12
  • 2019-11-02
  • 1970-01-01
  • 2012-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多