Reputation: 1047
After i took a photo with the camera i save the image with the following code:
UIImageWriteToSavedPhotosAlbum(image, self,"image:didFinishSavingWithError:contextInfo:", nil)
This saves the image in the camera roll. Additionally i want to save the URL to this saved image in Core Data. Is it possible to retrieve the URL (or the Path) to so that i only need to save this URL and not the full image in Core Data?
Upvotes: 14
Views: 8370
Reputation: 14294
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
})
}
Upvotes: 2
Reputation: 1047
After reading a lot of answers written in ObjectivC i finally figured out how to write this in Swift with Xcode 6.2:
ALAssetsLibrary().writeImageToSavedPhotosAlbum(image.CGImage, orientation: ALAssetOrientation(rawValue: image.imageOrientation.rawValue)!,
completionBlock:{ (path:NSURL!, error:NSError!) -> Void in
println("\(path)")
})
Upvotes: 9