【问题标题】:How do I save and show a Image with core data - swift 3如何保存和显示带有核心数据的图像 - swift 3
【发布时间】:2016-10-31 12:27:14
【问题描述】:

我正在Swift 3 - xcode 8 做一个项目,我正在尝试使用核心数据在数据库表“用户”中保存和显示一些图像。 此图片是他个人资料中的用户照片。

现在我已经设法保存字符串并从核心数据中显示它们,但我在处理图像时遇到了问题。

这是我目前所拥有的:

将用户添加到核心数据中

func addUser() {
    let app = UIApplication.shared.delegate as! AppDelegate
    let context = app.persistentContainer.viewContext
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
    request.returnsObjectsAsFaults = false

    let newUser = NSEntityDescription.insertNewObject(forEntityName: "Users", into: context)

    if (firstName.text == "" && lastName.text == "" && contact.text == "" && email.text == "") { //if we have a user profile delete it
        deleteUser()
    } else { // add a new user profile
        newUser.setValue(firstName.text, forKey: "firstName")
        newUser.setValue(lastName.text, forKey: "lastName")
        newUser.setValue(contact.text, forKey: "contact")
        newUser.setValue(email.text, forKey: "email")

        //newUser.setValue(imageView.image, forKey: "photo")
        //let imgUrl = UIImagePickerControllerReferenceURL as! NSURL
        let img = UIImage(named: "f.png")
        let imgData = UIImageJPEGRepresentation(img!, 1)

        newUser.setValue(imgData, forKey: "photo")

        print ("Data added in Users")
    }
    do {
        try context.save()
        //print("saved!!!")
        Alert.show(title: "Success", message: "Profile Saved", vc: self)
    } catch {
       // print ("Error")
        Alert.show(title: "Error", message: "Profile not Saved", vc: self)
    }
}

显示用户来自core data

func showUser() {
    let app = UIApplication.shared.delegate as! AppDelegate
    let context = app.persistentContainer.viewContext
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")

    request.returnsObjectsAsFaults = false

    do {
        let results = try context.fetch(request)

        if results.count > 0 {
            print("Profile: Data Found:")
            for result in results as! [NSManagedObject] {
               if let firstNameinData = result.value(forKey: "firstName") as? String{
                    firstName.text = firstNameinData
                    print(firstNameinData)
                }

                if let lastNameinData = result.value(forKey: "lastName") as? String{
                    lastName.text = lastNameinData
                    print(lastNameinData)
                }

                if let contactinData = result.value(forKey: "contact") as? String{
                    contact.text = contactinData
                    print(contactinData)
                }

                if let emailinData = result.value(forKey: "email") as? String{
                    email.text = emailinData
                    print(emailinData)
                }

                if let photoinData = result.value(forKey: "photo") as? UIImage{
                    imageView.image = photoinData
                }
            }
        } else {  // if there is not a user profile
            firstName.text = ""
            lastName.text = ""
            contact.text = ""
            email.text = ""
            print("Profile : No data found")
        }
        //print("Loaded!!!")
    } catch {
        print ("Error Loading")
    }
}

我无法显示我保存的图像。 你有什么建议吗?

编辑:Xcode 给我这个消息“与 assetsd 的连接被中断或 assetsd 死了”

【问题讨论】:

  • 您为属性photo 保存了(NS)Data 对象,而不是UIImage 对象。所以我的猜测是:if let photoinData = result.value(forKey: "photo") as? NSData{imageView.image = UIImage(data: photoinData);},或者类似的东西应该可以工作。
  • 我做到了。很好,谢谢:)
  • 如果让 photoinData = result.value(forKey: "photo") as? NSData{ ImageView.image = UIImage(data: photoinData as Data) }
  • 还有一个问题:我正在插入一个用户从他的手机中选择的图像,其中包含一个 imagePickerController。如何添加该图像? (而不是 f.png)。

标签: swift xcode swift3 xcode8


【解决方案1】:

Users 的属性photo(NS)Data,就像你在那里所做的那样,转换

UIImage 变成NSData

let img = UIImage(named: "f.png")
let imgData = UIImageJPEGRepresentation(img!, 1)
newUser.setValue(imgData, forKey: "photo")

当您检索信息时,您所做的就像 photoUIImage 对象:

if let photoinData = result.value(forKey: "photo") as? UIImage{
    imageView.image = photoinData
}

根据前几行,这不符合逻辑。应该是这样的:

if let imageData = result.value(forKey: "photo") as? NSData {
    if let image = UIImage(data:imageData) as? UIImage {
        imageView.image = image
    }
}

注意:我不会说 Swift,所以建议的代码可能无法编译,但你应该明白哪里出了问题以及需要做什么。

【讨论】:

    【解决方案2】:

    Larme 几乎可以找到它,但不是这样:

    if let image = UIImage(data:imageData) as? UIImage
    

    这样做:

    if let image = UIImage(data: imageData as Data)
    

    【讨论】:

      【解决方案3】:

      希望我能帮助你。对我来说工作得很好

      var results :[Any] = []
      
      let image = UIImage(named: "image.png")
              //this is the line that appears to be wrong
              let imageData = UIImagePNGRepresentation(image!) as NSData?
      
      
      
              guard let appDelegate =
                  UIApplication.shared.delegate as? AppDelegate else {
                      return
              }
      
      
              // 1
              let managedContext =
                  appDelegate.persistentContainer.viewContext
      
              // 2
              let entity =
                  NSEntityDescription.entity(forEntityName: "Image",
                                             in: managedContext)!
      
              let person = NSManagedObject(entity: entity,
                                           insertInto: managedContext)
      
              // 3
              person.setValue(imageData, forKeyPath: "name")
      
              // 4
              do {
                  try managedContext.save()
                  results.append(person)
      
      
              } catch let error as NSError {
                  print("Could not save. \(error), \(error.userInfo)")
              }
      

      【讨论】:

        【解决方案4】:

        希望这会对您有所帮助。首先,我也很困惑将图像存储在核心数据中。

        这用于将图像保存在coreData中

        首先创建 Nsmanaged 对象类

        class Item: NSManagedObject {
        
        
        }
        
        Declare the image as NSData
        
        import CoreData
        
        extension Item {
        
            @NSManaged var image: NSData?
            @NSManaged var name: String?
            @NSManaged var email: String?
        
        }
        

        现在转到要保存图像的视图控制器。

        class newViewController: UIViewController ,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
        
         var item : Item? = nil
        
            var imagePicker = UIImagePickerController()
        
            var PassImages = UIImage()
        
            @IBOutlet var name: UITextField!
        
            @IBOutlet var email: UITextField!
        
            @IBOutlet var photoclick: UIButton!
        
                var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        
        
            @IBAction func clickaction(_ sender: Any) {
        
                if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary){
                    print("Button capture")
        
                    let picker = UIImagePickerController()
                    picker.allowsEditing = true
                    picker.sourceType = .photoLibrary
                    picker.delegate = self  //Don't forget this line!
                    self.present(picker, animated: true, completion: nil)
        
        
                }
            }
        
        
            func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
                var selectedImage: UIImage?
                if let editedImage = info[.editedImage] as? UIImage {
                    selectedImage = editedImage
                    self.image.image = selectedImage!
                    picker.dismiss(animated: true, completion: nil)
                } else if let originalImage = info[.originalImage] as? UIImage {
                    selectedImage = originalImage
                    self.image.image = selectedImage!
                    picker.dismiss(animated: true, completion: nil)
                }
        
            }
        
        
            func imagePickerControllerDidCancel(picker: UIImagePickerController!) {
        
                self.dismiss(animated: true, completion: nil)
            }
        
            @IBOutlet var image: UIImageView!=nil
        
        
            @IBAction func submit(_ sender: Any) {
        
                if name.text != "" && email.text != ""
                {
        
                    let entityDescription = NSEntityDescription.entity(forEntityName: "Table", in: context)
        
                    let item = Item(entity: entityDescription!, insertInto: context)
        
                    item.name = name.text
                    item.email = email.text
        
                    item.image = image.image!.pngData()! as NSData
        
                    do {
                        try context.save()
                        print("saved this moc")
                    } catch {
                        return
                    }
        
         let UserDetailsVc = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
        
                    self.navigationController?.pushViewController(UserDetailsVc, animated: true)
        
                }
                else
                {
                    print("mail check")
                    let alertController1 = UIAlertController (title: "Fill Email id", message: "Enter valid email", preferredStyle: UIAlertController.Style.alert)
        
                    alertController1.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
                    present(alertController1, animated: true, completion: nil)
                }
            }
        
        override func viewDidLoad() {
        
                super.viewDidLoad()
        
                if item != nil {
                    name.text = item?.name
                    email.text = item?.email
                    image.image = UIImage(data: (item?.image)! as Data)
                }
            }
        

        此控制器用于获取所有内容

        class ViewController: UIViewController ,UITableViewDataSource,UITableViewDelegate,NSFetchedResultsControllerDelegate{
        
            var userarray: [Table] = []
        
            func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                return userarray.count
            }
        
            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
                let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
        
                let name = userarray[indexPath.row]
                cell.username.text = name.name
        
                cell.showImage?.image = UIImage(data: (name.image)!)
        
                 return cell
            }
        
            @IBOutlet var table: UITableView!
            override func viewDidLoad() {
                super.viewDidLoad()
        
                fetchData()
            }
        
            override func viewWillAppear(_ animated: Bool) {
                fetchData()
            }
        
            func fetchData(){
        
                let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        
                do {
                    userarray = try context.fetch(Table.fetchRequest())
                    print(userarray,"user")
        
                }catch{
                    print("error")
                }
        
            }
        
        }
        

        【讨论】:

          猜你喜欢
          • 2017-07-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-01
          • 1970-01-01
          • 2017-08-01
          相关资源
          最近更新 更多