Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS & Swift - How can I get and save a UIImage from the user?

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.

like image 424
quillford Avatar asked Nov 02 '14 22:11

quillford


2 Answers

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.

like image 181
Brian Tracy Avatar answered Oct 09 '22 20:10

Brian Tracy


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
    })
}
like image 44
Alvin George Avatar answered Oct 09 '22 21:10

Alvin George