0

In my app, the user selects an image from camera roll, and it is saved in a document directory. The image is then displayed on the ViewController where they selected the image. I want the image to be appended to a UICollectionView. How can I access the image/append the image from the documentDirectory? Please see my code below. Let me know if you need other pieces of my project.

DetailViewController(Where I initially display the photo):

class DetailViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

...

var imageStore: ImageStore!

@IBAction func takePicture(sender: UIBarButtonItem) {

    let imagePicker = UIImagePickerController()

    if UIImagePickerController.isSourceTypeAvailable(.Camera) {
        imagePicker.sourceType = .Camera
    } else {
        imagePicker.sourceType = .PhotoLibrary
    }
    imagePicker.delegate = self

    presentViewController(imagePicker, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: AnyObject]) {

    let image = info[UIImagePickerControllerOriginalImage] as! UIImage

    imageStore.setImage(image, forKey: item.itemKey)

    imageView.image = image

    dismissViewControllerAnimated(true, completion: nil)
}

override func viewWillAppear(animated: Bool) {

super.viewWillAppear(animated)

let key = item.itemKey

if let imageToDisplay = imageStore.imageForKey(key) {
   imageView.image = imageToDisplay
   }
}

ImageStore(How I initially store the photo):

import UIKit

class ImageStore: NSObject {

let cache = NSCache()

func setImage(image: UIImage, forKey key: String) {
    cache.setObject(image, forKey: key)

    let imageURL = imageURLForKey(key)

    if let data = UIImageJPEGRepresentation(image, 0.5) {
        data.writeToURL(imageURL, atomically: true)
    }
}
func imageForKey(key: String) -> UIImage? {
    if let existingImage = cache.objectForKey(key) as? UIImage {
        return existingImage
    }

    let imageURL = imageURLForKey(key)
    guard let imageFromDisk = UIImage(contentsOfFile: imageURL.path!) else {
        return nil
    }

    cache.setObject(imageFromDisk, forKey: key)
    return imageFromDisk
}

func deleteImageForKey(key: String) {
    cache.removeObjectForKey(key)

    let imageURL = imageURLForKey(key)
    do {
        try NSFileManager.defaultManager().removeItemAtURL(imageURL)
    }
    catch let deleteError {
        print("Error removing the image from disk: \(deleteError)")
    }
}

func imageURLForKey(key: String) -> NSURL {
    let documentsDirectories =
    NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
    let documentDirectory = documentsDirectories.first!

    return documentDirectory.URLByAppendingPathComponent(key)
  }

}

UICollectionView:

import UIKit

class PhotosViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

var collectionView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    layout.itemSize = CGSize(width: 300, height: 490)

    collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    collectionView.dataSource = self
    collectionView.delegate = self
    collectionView!.registerClass(FoodCell.self, forCellWithReuseIdentifier: "Cell")
    collectionView.backgroundColor = UIColor.whiteColor()
    self.view.addSubview(collectionView)
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return images.count
}

var images: [UIImage] = [

]

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! FoodCell
    cell.textLabel.text = ""
    cell.imageView.image = images[indexPath.row]
    return cell
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
    print("User tapped on item \(indexPath.row)")
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
}
Allie
  • 57
  • 7

1 Answers1

0

You can try to save and get your image by this way:

//Save image
let img = UIImage() // Image from your picker
let data = UIImagePNGRepresentation(img)!
do {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    try data.writeToFile("\(documentsPath)myImage", options: [])

} catch {
    print("Error")
}

// Get image
do {
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let readData = try NSData(contentsOfFile: "\(documentsPath)myImage", options: [])
    let retreivedImage = UIImage(data: readData)
}
catch {
    print("Error")
}

Same way as https://stackoverflow.com/a/35685943/2894160

Community
  • 1
  • 1
Jimmy James
  • 825
  • 12
  • 28
  • I tried this, but it did not properly save the image. After I dismissed the DetailViewController and then went back into it, the image no longer displayed. – Allie Dec 10 '16 at 04:22