How to save and display an image with master data - swift 3

I am doing a project in Swift 3- xcode 8and I am trying to use basic data to save and show some images in the "users" database table. This image is a photograph of a user in his profile.

Now I managed to save the rows and show them from the main data, but I have problems with image processing.

This is what I still have:

Adding users to master 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 fromcore 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 can not show the image that I saved. Do you have any tips?

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

+4
4

photo of 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, , , .

+7

, .

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

Larme , :

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

:

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

Hope this helps you. Firstly, I was also very confused about storing the image in the main data.

This is used to save the image in coreData.

First create an Nsmanaged Object Class

class Item: NSManagedObject {


}

Declare the image as NSData

import CoreData

extension Item {

    @NSManaged var image: NSData?
    @NSManaged var name: String?
    @NSManaged var email: String?

}

Now go to View Controller, you want to save the image.

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

This controller is used to get everything.

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

    }

}
+1
source

Source: https://habr.com/ru/post/1659406/


All Articles