9

I am writing a Swift app for iOS. I want to know how to get an image from the user's camera roll (or whatever they're calling it these days) and save it locally within the app so that I can reference it later. How would one go about this? As an example, let's say I want to get the image and set it as the image for a UIImageView in my storyboard.

quillford
  • 111
  • 1
  • 1
  • 6

5 Answers5

5

This is exactly what UIImagePickerController combined with NSUserDefaults will do.

For you it will be a two part task. First you will have to capture the image with a UIImagePickerController and then either store it in their photo library, or store it on their device with NSUserDefaults.

To store an image with NSUserDefaults, see this question.

Community
  • 1
  • 1
Brian Tracy
  • 6,576
  • 2
  • 28
  • 46
4

Here is my combination.

Saving Image:

let imageData = NSData(data:UIImagePNGRepresentation(pickedimage))
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var docs: String = paths[0] as! String
let fullPath = docs.stringByAppendingPathComponent("yourNameImg.png")
let result = imageData.writeToFile(fullPath, atomically: true)

print(fullPath)

Get Image:

let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask    = NSSearchPathDomainMask.UserDomainMask
if let paths            = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
{
    if paths.count > 0
    {
        if let dirPath = paths[0] as? String
        {
            let readPath = dirPath.stringByAppendingPathComponent("yourNameImg.png")
            let image    = UIImage(contentsOfFile: readPath)

            UploadImagePreview.image = image
        }
    }
}

We can try with Photos Framework to fetch the last saved image.

var fetchOptions: PHFetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]

var fetchResult = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: fetchOptions)

if (fetchResult.firstObject != nil) {
    var lastAsset: PHAsset = fetchResult.lastObject as! PHAsset

    PHImageManager.defaultManager().requestImageForAsset(lastAsset, targetSize: self.UploadImagePreview.bounds.size, contentMode: PHImageContentMode.AspectFill, options: PHImageRequestOptions(), resultHandler: { (result, info) -> Void in
        self.UploadImagePreview.image = result
    })
}
Pang
  • 8,605
  • 144
  • 77
  • 113
A.G
  • 13,048
  • 84
  • 61
2

Ray Wenderlich has a great tutorial for using a UIImagePickerController to select an image and then using the AssetsLibrary to save to an album.

There is also info on using image filters that is more than you asked for in the tutorial.

sudo make install
  • 5,341
  • 3
  • 26
  • 45
Steve Rosenberg
  • 18,504
  • 7
  • 42
  • 50
  • The only way I know to not conform to the UIImagePickerControllerDelegate is to not also conform to UINavigationControllerDelegate. The UIPicker needs a nav controller. – Steve Rosenberg Nov 03 '14 at 02:51
2

Once you get the UIImage object, you can save the image in a doc dir with the following code

let imageData = NSData(data:UIImagePNGRepresentation(wineImage.image))
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var docs: String = paths[0] as! String
let fullPath = docs.stringByAppendingPathComponent("yourNameImg.png")
let result = imageData.writeToFile(fullPath, atomically: true)
Community
  • 1
  • 1
dpizzuto
  • 402
  • 1
  • 5
  • 14
0

You should definitely use a UIImagePickerController as Brian mentioned, once you have the selected image use this file manager approach. I don't recommend using NSUserDefaults to store images as it goes against Apple guidelines:

let imageData = UIImagePNGRepresentation(selectedImage)
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let imagePath = paths.stringByAppendingPathComponent("cached.png")

if !imageData.writeToFile(imagePath, atomically: false)
{
    println("not saved")
} else {
    println("saved")
    NSUserDefaults.standardUserDefaults().setObject(imagePath, forKey: "imagePath")
}
Ever Uribe
  • 399
  • 3
  • 12