如何使用核心数据保存和显示图像 - swift 3

时间:2016-10-31 12:27:15

标签: swift xcode swift3 xcode8

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

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

这是我到目前为止所做的:

将USERS添加到核心数据中

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给我这条消息“资产连接中断或资产已经中断”

4 个答案:

答案 0 :(得分:9)

photo的属性Users(NS)Data,正如您所做的那样,转换

UIImage加入NSData

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

当您检索信息时,您就像photo是一个UIImage对象:

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,所以建议的代码可能无法编译,但你应该知道什么是错的,需要做些什么。

答案 1 :(得分:1)

希望我帮助你。为我工作

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)")
        }

答案 2 :(得分:1)

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

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

这样做:

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

答案 3 :(得分:1)

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

这用于将图像保存在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?

}

现在转到要保存图像的View Controller。

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")
        }

    }

}