Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save and show a Image with core data - swift 3

I am doing a project in Swift 3 - xcode 8, and I am trying to use core data to save and show some images in a data base table "users". This image is the user photo in his profile.

Now I've managed to save strings and showing them from core data but I am having problems in working this out with images.

This is what I have so far:

Adding USERS into core data

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

Showing Users from 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")
    }
}

I cannot show the image I have saved. Do you have any tips?

EDIT: Xcode gives me this message "Connection to assetsd was interrupted or assetsd died"

like image 805
H.N. Avatar asked Oct 31 '16 12:10

H.N.


Video Answer


2 Answers

The property photo of Users is (NS)Data, as you do there, converting the

UIImage into NSData.

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

While when you retrieve the info, you are doing like photo was a UIImage object:

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

This is not logical according to previous lines. It should be something like that:

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

Note: I don't speak Swift, so the proposed code may not compile, but you should get the idea of what's wrong and what's need to be done.

like image 95
Larme Avatar answered Sep 27 '22 22:09

Larme


Larme has it almost spot on, but instead of this:

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

do this:

if let image = UIImage(data: imageData as Data)
like image 45
Rolf Cosmo Anthony Avatar answered Sep 27 '22 22:09

Rolf Cosmo Anthony