Im trying to get the image name using PHAssets. But I couldn't find metadata for filename or any method to get the image name. Is there a different way to get the file name?
I know the question has already been answered, but I figured I would provide another option:
extension PHAsset {
var originalFilename: String? {
var fileName: String?
if #available(iOS 9.0, *) {
let resources = PHAssetResource.assetResources(for: self)
if let resource = resources.first {
fileName = resource.originalFilename
}
}
if fileName == nil {
/// This is an undocumented workaround that works as of iOS 9.1
fileName = self.value(forKey: "filename") as? String
}
return fileName
}
}
If you want to get the image name (for example name of last photo in Photos) like IMG_XXX.JPG, you can try this:
PHAsset *asset = nil;
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:YES]];
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
if (fetchResult != nil && fetchResult.count > 0) {
// get last photo from Photos
asset = [fetchResult lastObject];
}
if (asset) {
// get photo info from this asset
PHImageRequestOptions * imageRequestOptions = [[PHImageRequestOptions alloc] init];
imageRequestOptions.synchronous = YES;
[[PHImageManager defaultManager]
requestImageDataForAsset:asset
options:imageRequestOptions
resultHandler:^(NSData *imageData, NSString *dataUTI,
UIImageOrientation orientation,
NSDictionary *info)
{
NSLog(#"info = %#", info);
if ([info objectForKey:#"PHImageFileURLKey"]) {
// path looks like this -
// file:///var/mobile/Media/DCIM/###APPLE/IMG_####.JPG
NSURL *path = [info objectForKey:#"PHImageFileURLKey"];
}
}];
}
Hope it helps.
In Swift the code will look like this
PHImageManager.defaultManager().requestImageDataForAsset(asset, options: PHImageRequestOptions(), resultHandler:
{
(imagedata, dataUTI, orientation, info) in
if info!.keys.contains(NSString(string: "PHImageFileURLKey"))
{
let path = info![NSString(string: "PHImageFileURLKey")] as! NSURL
}
})
Swift 4:
let fetchResult = PHAsset.fetchAssets(with: .image, options: nil)
if fetchResult.count > 0 {
if let asset = fetchResult.firstObject {
let date = asset.creationDate ?? Date()
print("Creation date: \(date)")
PHImageManager.default().requestImageData(for: asset, options: PHImageRequestOptions(),
resultHandler: { (imagedata, dataUTI, orientation, info) in
if let info = info {
if info.keys.contains(NSString(string: "PHImageFileURLKey")) {
if let path = info[NSString(string: "PHImageFileURLKey")] as? NSURL {
print(path)
}
}
}
})
}
}
One more option is:
[asset valueForKey:#"filename"]
The "legality" of this is up to you to decide.
Easiest solution for iOS 9+ in Swift 4 (based on skims answer):
extension PHAsset {
var originalFilename: String? {
return PHAssetResource.assetResources(for: self).first?.originalFilename
}
}
For Swift
asset?.value(forKey: "filename") as? String
For objective C
[asset valueForKey:#"filename"]
Simplest answer with Swift when you have reference url to an asset:
if let asset = PHAsset.fetchAssetsWithALAssetURLs([referenceUrl], options: nil).firstObject as? PHAsset {
PHImageManager.defaultManager().requestImageDataForAsset(asset, options: nil, resultHandler: { _, _, _, info in
if let fileName = (info?["PHImageFileURLKey"] as? NSURL)?.lastPathComponent {
//do sth with file name
}
})
}
SWIFT4:
first import Photos
if let asset = PHAsset.fetchAssets(withALAssetURLs: [info[UIImagePickerControllerReferenceURL] as! URL],
options: nil).firstObject {
PHImageManager.default().requestImageData(for: asset, options: nil, resultHandler: { _, _, _, info in
if let fileName = (info?["PHImageFileURLKey"] as? NSURL)?.lastPathComponent {
print("///////" + fileName + "////////")
//do sth with file name
}
})
}
What you really looking for is the localIdentifier which is a unique string that persistently identifies the object.
Use this string to find the object by using the:
fetchAssetsWithLocalIdentifiers:options:, fetchAssetCollectionsWithLocalIdentifiers:options:, or fetchCollectionListsWithLocalIdentifiers:options: method.
More information is available here
Related
My goal (besides learning how to write an iOS app extension) is to allow a user to share an image using the share button from a variety of apps including Photos and automatically rename them. Lastly then I want to save the image to the "documents" folder of the app for further use.
I'm having some problems trying to get the actual didSelectPost portion working since it seems that, unlike Objective-C examples I've seen, the loadItem operation returns a NSURL instead of an UIImage. When attempting to copy the NSUrl to my apps documents folder I get an error:
Error Domain=NSCocoaErrorDomain Code=260 "The file “IMG_0941.JPG”
couldn’t be opened because there is no such file."
UserInfo={NSFilePath=file:///var/mobile/Media/PhotoData/OutgoingTemp/B79263E5-9512-4317-9C5D-817D7EBEFA9A/RenderedPhoto/IMG_0941.JPG,
NSUnderlyingError=0x283f89080 {Error Domain=NSPOSIXErrorDomain Code=2
"No such file or directory"}}
This happens when I push the share button on a photo in the "photos" app, tap my extension and then press the "post" button.
I get the same error regardless if it's running in a simulator or real device.
Here's my hacked together progress so far:
override func didSelectPost() {
// This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.
let inputItem = extensionContext?.inputItems.first as! NSExtensionItem
let attachment = inputItem.attachments!.first!
if attachment.hasItemConformingToTypeIdentifier(kUTTypeJPEG as String) {
attachment.loadItem(forTypeIdentifier: kUTTypeJPEG as String, options: nil) { data, error in
var image: UIImage?
if let someUrl = data as? NSURL {
do {
// a ends up being nil in both of these cases
let a = NSData(contentsOfFile: someUrl.absoluteString!)
image = UIImage(data: a as! Data)
// let a = try Data(contentsOf: someUrl)
// image = UIImage(contentsOfFile: someUrl.absoluteString)
} catch {
print(error)
}
} else if let someImage = data as? UIImage {
image = someImage
}
if let someImage = image {
guard let compressedImagePath = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?.appendingPathComponent("theimage.jpg", isDirectory: false) else {
return
}
let compressedImageData = someImage.jpegData(compressionQuality: 1)
guard (try? compressedImageData?.write(to: compressedImagePath)) != nil else {
return
}
} else {
print("Bad share data")
}
}
}
// Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context.
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
Notice I'm casting the img variable as an NSURL. I've tried to cast it as a UIImage but that throws an exception.
I have some other things I'd like to do to the image, like read it's EXIF data but for now this is what I have. Any suggestions would be great as I'm really struggling to wrap my head around and learn this environment.
Similar but unsuccessful posts I've tried, notice they are all Objective-C:
iOS Share Extension issue when sharing images from Photo library
Share image using share extension in ios8
How to add my app to the share sheet action
[edit] Matched the layout of one of the better answers, still with no luck.
I have review your code and there is some mistake in the code. I have fixed it .
Replace your code with it
func share() {
let inputItem = extensionContext!.inputItems.first! as! NSExtensionItem
let attachment = inputItem.attachments!.first as! NSItemProvider
if attachment.hasItemConformingToTypeIdentifier( kUTTypeImage as String) {
attachment.loadItem(forTypeIdentifier: kUTTypeImage as String, options: [:]) { (data, error) in
var image: UIImage?
if let someURl = data as? URL {
image = UIImage(contentsOfFile: someURl.path)
}else if let someImage = data as? UIImage {
image = someImage
}
if let someImage = image {
guard let compressedImagePath = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?.appendingPathComponent("shareImage.jpg", isDirectory: false) else {
return
}
let compressedImageData = UIImageJPEGRepresentation(someImage, 1)
guard (try? compressedImageData?.write(to: compressedImagePath)) != nil else {
return
}
}else{
print("bad share data")
}
}
}
}
I have the same issue. The solution I was able to implement:
Get URL to image. This URL is useless because I got 260 error when try to load image using this URL. Interesting that this comes after some recent updates because it works before
Get file name with extension from this URL
Iterate over all images in user's photo library and find the image name == name from ULR
Extract the image data
- (void)didSelectPost {
for (NSItemProvider* itemProvider in ((NSExtensionItem*)self.extensionContext.inputItems[0]).attachments ) {
// get type of file extention (jpeg, file, url, png ...)
NSArray *registeredTypeIdentifiers = itemProvider.registeredTypeIdentifiers;
if ([itemProvider hasItemConformingToTypeIdentifier:registeredTypeIdentifiers.firstObject]) {
[itemProvider loadItemForTypeIdentifier:registeredTypeIdentifiers.firstObject options:nil completionHandler:^(id<NSSecureCoding> item, NSError *error) {
NSData *imgData;
NSString* imgPath = ((NSURL*) item).absoluteString;
if(imgPath == nil)
imgPath = [NSString stringWithFormat:#"%#", item];
NSCharacterSet* set = [NSCharacterSet URLHostAllowedCharacterSet];
NSString* imgPathEscaped = [imgPath stringByAddingPercentEncodingWithAllowedCharacters:set];
NSString* fileName = [imgPath lastPathComponent];
NSError* error2 = nil;
//try load from file path
__block NSData* data2 = [NSData dataWithContentsOfFile:imgPath options: NSDataReadingUncached error:&error2];
if(data2 == nil) //try load as URL
data2 = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgPath] options: NSDataReadingUncached error:&error2];
if(data2 == nil) //all failed so try hacky way
{
NSString* searchFilename = [fileName lowercaseString];
PHFetchResult *results = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];
[results enumerateObjectsUsingBlock:^(PHAsset *obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSArray* resources = [PHAssetResource assetResourcesForAsset:obj];
NSString* fileName2 = [NSString stringWithFormat:#"%#", ((PHAssetResource*)resources[0]).originalFilename].lowercaseString;
if ([fileName2 isEqual:searchFilename])
{
NSLog(#"found %#", fileName2);
PHImageManager* mgr = [PHImageManager defaultManager];
PHImageRequestOptions * options = [PHImageRequestOptions alloc];
options.synchronous = YES;
[mgr requestImageDataForAsset:obj options:options resultHandler:^(NSData * _Nullable imageData33, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info)
{
//imageData33 is your image
data2 = imageData33;
}];
}
}];
}
}];
}
}
// Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context.
[self.extensionContext completeRequestReturningItems:#[] completionHandler:nil];
}
func getPhotofolder() -> String{
let fileManager = FileManager.default
let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("hsafetyPhoto")
if !fileManager.fileExists(atPath: paths){
try! fileManager.createDirectory(atPath: paths, withIntermediateDirectories: true, attributes: nil)
}else{
print("Already dictionary created.")
}
return paths
}
func saveImageDocumentDirectory(photo : UIImage, photoUrl : String) -> Bool{
let fileManager = FileManager.default
let paths = Utility.getPhotofolder().stringByAppendingPathComponent(pathComponent: photoUrl)
print("image's path \(paths)")
if !fileManager.fileExists(atPath: paths){
print("file already exits \(paths)")
let imageData = UIImageJPEGRepresentation(photo, 0.5)
fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)
if !fileManager.fileExists(atPath: paths){
return false
}else{
return true
}
}else{
print(paths)
let imageData = UIImageJPEGRepresentation(photo, 0.5)
fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)
if !fileManager.fileExists(atPath: paths){
return false
}else{
return true
}
}
}
func showimage(image_name : String) {
let documentsUrl = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
let imgUrl = documentsUrl.appendingPathComponent(image_name)
if(FileManager.default.fileExists(atPath:imgUrl.path))
{
do {
let data = try Data(contentsOf:imgUrl)
self.imageView.image = UIImage(data:data)
}catch {
print(error)
} } else{
self.imageView.image = UIImage(named:"default.jpg") //Display any default image
}
}
In modern iOS (2017),
here's actually the only way I know to save an image to the iOS photos system, and get the filename/path.
import UIKit
import Photos
func saveTheImage... () {
UIImageWriteToSavedPhotosAlbum(yourUIImage, self,
#selector(Images.image(_:didFinishSavingWithError:contextInfo:)),
nil)
}
func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
guard error == nil else {
print("Couldn't save the image!")
return
}
doGetFileName()
}
func doGetFileName() {
let fo: PHFetchOptions = PHFetchOptions()
fo.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
let r = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fo)
if let mostRecentThingy = r.firstObject {
PHImageManager.default().requestImageData(
for: mostRecentThingy,
options: PHImageRequestOptions(),
resultHandler: { (imagedata, dataUTI, orientation, info) in
if info!.keys.contains("PHImageFileURLKey") {
let path = info!["PHImageFileURLKey"] as! NSURL
print("Holy cow. The path is \(path)")
}
else { print("bizarre problem") }
})
}
else { print("unimaginable catastrophe") }
}
The problem with this is that it fails in racetrack conditions.
This is amazingly unwieldy, and it seems worrysome in a number of ways.
Is it really the way to go, today?
extension PHPhotoLibrary {
func save(imageData: Data, withLocation location: CLLocation?) -> Promise<PHAsset> {
var placeholder: PHObjectPlaceholder!
return Promise { fullfil, reject in
performChanges({
let request = PHAssetCreationRequest.forAsset()
request.addResource(with: .photo, data: imageData, options: .none)
request.location = location
placeholder = request.placeholderForCreatedAsset
}, completionHandler: { (success, error) -> Void in
if let error = error {
reject(error)
return
}
guard let asset = PHAsset.fetchAssets(withLocalIdentifiers: [placeholder.localIdentifier], options: .none).firstObject else {
reject(NSError())
return
}
fullfil(asset)
})
}
}
}
I think you can do this with PHPhotoLibrary and PHObjectPlaceholder.
You just saved image programmatically, so you can get the image from camera and save it with your path:
//save image in Document Derectory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"Get Path : %#",documentsDirectory);
//create Folder if Not Exist
NSError *error = nil;
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/YourFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
NSString *yourPhotoName=#"YourPhotoName";
NSString* path= [dataPath stringByAppendingString:[NSString stringWithFormat:#"/%#.png",yourPhotoName]];
NSData* imageData = UIImagePNGRepresentation(imageToSaved); //which got from camera
[imageData writeToFile:path atomically:YES];
imagePath = path;
NSLog(#"Save Image Path : %#",imagePath);
Maybe this is a different approach but here's what I'm doing in my app and I'm satisfied with it:
func saveImage(image: UIImage, name: String) {
var metadata = [AnyHashable : Any]()
let iptcKey = kCGImagePropertyIPTCDictionary as String
var iptcMetadata = [AnyHashable : Any]()
iptcMetadata[kCGImagePropertyIPTCObjectName as String] = name
metadata[iptcKey] = iptcMetadata
let library = ALAssetsLibrary()
library.writeImage(toSavedPhotosAlbum: image.cgImage, metadata: metadata) { url, error in
// etc...
}
}
If you don't want to use ALAssetsLibrary, you'll probably be interested in this answer.
I came through the following link which demonstrated how to copy file from Gallery to application or other directory (in right answer):
How to copy an image file from iOS Photo Library (ALAssetsLibrary) to the local directory of an App?
But with ALAssetsLibrary class documentation Apple said its now deprecated as of iOS 9.0 instead use Photos framework.
The Assets Library framework is deprecated as of iOS 9.0. Instead, use
the Photos framework instead, which in iOS 8.0 and later provides more
features and better performance for working with a user’s photo
library. For more information, see Photos Framework Reference.
How I can use Photos framework to copy assets from Gallery to other URL?
This seems fairly easy. I added an example code for someone whom it may help:
var item: PHAsset! // you update with actual PHAsset at runtime
let docuPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.ApplicationDirectory, NSSearchPathDomainMask.UserDomainMask, true) as NSArray
let targetImgeURL = (docuPath[0] as! String) + "/IMG_0005.JPG"
let phManager = PHImageManager.defaultManager()
let options = PHImageRequestOptions()
options.synchronous = true; // do it if you want things running in background thread
phManager.requestImageDataForAsset(item, options: options)
{ imageData,dataUTI,orientation,info in
if let newData:NSData = imageData
{
try! newData.writeToFile(targetImgeURL, atomically: true)
}
}
Here is the Objective C solution.
-(NSURL*)createVideoCopyFromReferenceUrl:(NSURL*)inputUrlFromVideoPicker{
NSURL __block *videoURL;
PHFetchResult *phAssetFetchResult = [PHAsset fetchAssetsWithALAssetURLs:#[inputUrlFromVideoPicker ] options:nil];
PHAsset *phAsset = [phAssetFetchResult firstObject];
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
[[PHImageManager defaultManager] requestAVAssetForVideo:phAsset options:nil resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
if ([asset isKindOfClass:[AVURLAsset class]]) {
NSURL *url = [(AVURLAsset *)asset URL];
NSLog(#"Final URL %#",url);
NSData *videoData = [NSData dataWithContentsOfURL:url];
// optionally, write the video to the temp directory
NSString *videoPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"%f.mp4",[NSDate timeIntervalSinceReferenceDate]]];
videoURL = [NSURL fileURLWithPath:videoPath];
BOOL writeResult = [videoData writeToURL:videoURL atomically:true];
if(writeResult) {
NSLog(#"video success");
}
else {
NSLog(#"video failure");
}
dispatch_group_leave(group);
// use URL to get file content
}
}];
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
return videoURL;
}
In Swift use below set of code
import Photos
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
self.dismissViewControllerAnimated(true, completion: nil)
if let referenceURL = info[UIImagePickerControllerReferenceURL] as? NSURL {
let fetchResult = PHAsset.fetchAssetsWithALAssetURLs([referenceURL], options: nil)
if let phAsset = fetchResult.firstObject as? PHAsset {
PHImageManager.defaultManager().requestAVAssetForVideo(phAsset, options: PHVideoRequestOptions(), resultHandler: { (asset, audioMix, info) -> Void in
if let asset = asset as? AVURLAsset {
let videoData = NSData(contentsOfURL: asset.URL)
// optionally, write the video to the temp directory
let videoPath = NSTemporaryDirectory() + "tmpMovie.MOV"
let videoURL = NSURL(fileURLWithPath: videoPath)
let writeResult = videoData?.writeToURL(videoURL, atomically: true)
if let writeResult = writeResult where writeResult {
print("success")
}
else {
print("failure")
}
}
})
}
}
}
Im trying to get the image name using PHAssets. But I couldn't find metadata for filename or any method to get the image name. Is there a different way to get the file name?
I know the question has already been answered, but I figured I would provide another option:
extension PHAsset {
var originalFilename: String? {
var fileName: String?
if #available(iOS 9.0, *) {
let resources = PHAssetResource.assetResources(for: self)
if let resource = resources.first {
fileName = resource.originalFilename
}
}
if fileName == nil {
/// This is an undocumented workaround that works as of iOS 9.1
fileName = self.value(forKey: "filename") as? String
}
return fileName
}
}
If you want to get the image name (for example name of last photo in Photos) like IMG_XXX.JPG, you can try this:
PHAsset *asset = nil;
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:YES]];
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
if (fetchResult != nil && fetchResult.count > 0) {
// get last photo from Photos
asset = [fetchResult lastObject];
}
if (asset) {
// get photo info from this asset
PHImageRequestOptions * imageRequestOptions = [[PHImageRequestOptions alloc] init];
imageRequestOptions.synchronous = YES;
[[PHImageManager defaultManager]
requestImageDataForAsset:asset
options:imageRequestOptions
resultHandler:^(NSData *imageData, NSString *dataUTI,
UIImageOrientation orientation,
NSDictionary *info)
{
NSLog(#"info = %#", info);
if ([info objectForKey:#"PHImageFileURLKey"]) {
// path looks like this -
// file:///var/mobile/Media/DCIM/###APPLE/IMG_####.JPG
NSURL *path = [info objectForKey:#"PHImageFileURLKey"];
}
}];
}
Hope it helps.
In Swift the code will look like this
PHImageManager.defaultManager().requestImageDataForAsset(asset, options: PHImageRequestOptions(), resultHandler:
{
(imagedata, dataUTI, orientation, info) in
if info!.keys.contains(NSString(string: "PHImageFileURLKey"))
{
let path = info![NSString(string: "PHImageFileURLKey")] as! NSURL
}
})
Swift 4:
let fetchResult = PHAsset.fetchAssets(with: .image, options: nil)
if fetchResult.count > 0 {
if let asset = fetchResult.firstObject {
let date = asset.creationDate ?? Date()
print("Creation date: \(date)")
PHImageManager.default().requestImageData(for: asset, options: PHImageRequestOptions(),
resultHandler: { (imagedata, dataUTI, orientation, info) in
if let info = info {
if info.keys.contains(NSString(string: "PHImageFileURLKey")) {
if let path = info[NSString(string: "PHImageFileURLKey")] as? NSURL {
print(path)
}
}
}
})
}
}
One more option is:
[asset valueForKey:#"filename"]
The "legality" of this is up to you to decide.
Easiest solution for iOS 9+ in Swift 4 (based on skims answer):
extension PHAsset {
var originalFilename: String? {
return PHAssetResource.assetResources(for: self).first?.originalFilename
}
}
For Swift
asset?.value(forKey: "filename") as? String
For objective C
[asset valueForKey:#"filename"]
Simplest answer with Swift when you have reference url to an asset:
if let asset = PHAsset.fetchAssetsWithALAssetURLs([referenceUrl], options: nil).firstObject as? PHAsset {
PHImageManager.defaultManager().requestImageDataForAsset(asset, options: nil, resultHandler: { _, _, _, info in
if let fileName = (info?["PHImageFileURLKey"] as? NSURL)?.lastPathComponent {
//do sth with file name
}
})
}
SWIFT4:
first import Photos
if let asset = PHAsset.fetchAssets(withALAssetURLs: [info[UIImagePickerControllerReferenceURL] as! URL],
options: nil).firstObject {
PHImageManager.default().requestImageData(for: asset, options: nil, resultHandler: { _, _, _, info in
if let fileName = (info?["PHImageFileURLKey"] as? NSURL)?.lastPathComponent {
print("///////" + fileName + "////////")
//do sth with file name
}
})
}
What you really looking for is the localIdentifier which is a unique string that persistently identifies the object.
Use this string to find the object by using the:
fetchAssetsWithLocalIdentifiers:options:, fetchAssetCollectionsWithLocalIdentifiers:options:, or fetchCollectionListsWithLocalIdentifiers:options: method.
More information is available here
I am making an app that takes pictures with AVFoundation and I want to save them to a custom album that I can then query and show in my app. (I'd prefer to not have them in the general photo roll, unless the user wants that) I can't really find anything showing how to do this in Swift... or at all. Is there a different way I am supposed to do this?
I found this example on SO but it doesn't make sense to me and I can't get it to work.
func savePhoto() {
var albumFound : Bool = false
var assetCollection: PHAssetCollection!
var photosAsset: PHFetchResult!
var assetThumbnailSize:CGSize!
// Create the album if does not exist (in viewDidLoad)
if let first_Obj:AnyObject = collection.firstObject{
//found the album
self.albumFound = true
self.assetCollection = collection.firstObject as PHAssetCollection
}else{
//Album placeholder for the asset collection, used to reference collection in completion handler
var albumPlaceholder:PHObjectPlaceholder!
//create the folder
NSLog("\nFolder \"%#\" does not exist\nCreating now...", albumName)
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let request = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(albumName)
albumPlaceholder = request.placeholderForCreatedAssetCollection
},
completionHandler: {(success:Bool, error:NSError!)in
NSLog("Creation of folder -> %#", (success ? "Success":"Error!"))
self.albumFound = (success ? true:false)
if(success){
let collection = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([albumPlaceholder.localIdentifier], options: nil)
self.assetCollection = collection?.firstObject as PHAssetCollection
}
})
}
let bundle = NSBundle.mainBundle()
let myFilePath = bundle.pathForResource("highlight1", ofType: "mov")
let videoURL:NSURL = NSURL.fileURLWithPath(myFilePath!)!
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0), {
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
//let createAssetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage
let createAssetRequest = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(videoURL)
let assetPlaceholder = createAssetRequest.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection, assets: self.photosAsset)
albumChangeRequest.addAssets([assetPlaceholder])
}, completionHandler: {(success, error)in
dispatch_async(dispatch_get_main_queue(), {
NSLog("Adding Image to Library -> %#", (success ? "Sucess":"Error!"))
//picker.dismissViewControllerAnimated(true, completion: nil)
})
})
})
}
Any help/explanations would be great!
This is how I do:
At the top:
import Photos
var image: UIImage!
var assetCollection: PHAssetCollection!
var albumFound : Bool = false
var photosAsset: PHFetchResult!
var assetThumbnailSize:CGSize!
var collection: PHAssetCollection!
var assetCollectionPlaceholder: PHObjectPlaceholder!
Creating the album:
func createAlbum() {
//Get PHFetch Options
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %#", "camcam")
let collection : PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)
//Check return value - If found, then get the first album out
if let _: AnyObject = collection.firstObject {
self.albumFound = true
assetCollection = collection.firstObject as! PHAssetCollection
} else {
//If not found - Then create a new album
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let createAlbumRequest : PHAssetCollectionChangeRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle("camcam")
self.assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection
}, completionHandler: { success, error in
self.albumFound = success
if (success) {
let collectionFetchResult = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([self.assetCollectionPlaceholder.localIdentifier], options: nil)
print(collectionFetchResult)
self.assetCollection = collectionFetchResult.firstObject as! PHAssetCollection
}
})
}
}
When saving the photo:
func saveImage(){
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(self.image)
let assetPlaceholder = assetRequest.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection, assets: self.photosAsset)
albumChangeRequest!.addAssets([assetPlaceholder!])
}, completionHandler: { success, error in
print("added image to album")
print(error)
self.showImages()
})
}
Showing the images from that album:
func showImages() {
//This will fetch all the assets in the collection
let assets : PHFetchResult = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: nil)
print(assets)
let imageManager = PHCachingImageManager()
//Enumerating objects to get a chached image - This is to save loading time
assets.enumerateObjectsUsingBlock{(object: AnyObject!,
count: Int,
stop: UnsafeMutablePointer<ObjCBool>) in
if object is PHAsset {
let asset = object as! PHAsset
print(asset)
let imageSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight)
let options = PHImageRequestOptions()
options.deliveryMode = .FastFormat
imageManager.requestImageForAsset(asset, targetSize: imageSize, contentMode: .AspectFill, options: options, resultHandler: {(image: UIImage?,
info: [NSObject : AnyObject]?) in
print(info)
print(image)
})
}
}
Answer in Objective-C and cleaned up a bit.
__block PHFetchResult *photosAsset;
__block PHAssetCollection *collection;
__block PHObjectPlaceholder *placeholder;
// Find the album
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.predicate = [NSPredicate predicateWithFormat:#"title = %#", #"YOUR_ALBUM_TITLE"];
collection = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum
subtype:PHAssetCollectionSubtypeAny
options:fetchOptions].firstObject;
// Create the album
if (!collection)
{
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetCollectionChangeRequest *createAlbum = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:#"YOUR_ALBUM_TITLE"];
placeholder = [createAlbum placeholderForCreatedAssetCollection];
} completionHandler:^(BOOL success, NSError *error) {
if (success)
{
PHFetchResult *collectionFetchResult = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:#[placeholder.localIdentifier]
options:nil];
collection = collectionFetchResult.firstObject;
}
}];
}
// Save to the album
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest *assetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:[UIImage imageWithData:imageData]];
placeholder = [assetRequest placeholderForCreatedAsset];
photosAsset = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
PHAssetCollectionChangeRequest *albumChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection
assets:photosAsset];
[albumChangeRequest addAssets:#[placeholder]];
} completionHandler:^(BOOL success, NSError *error) {
if (success)
{
NSString *UUID = [placeholder.localIdentifier substringToIndex:36];
self.photo.assetURL = [NSString stringWithFormat:#"assets-library://asset/asset.PNG?id=%#&ext=JPG", UUID];
[self savePhoto];
}
else
{
NSLog(#"%#", error);
}
}];
The bit at the end with the UUID was something I found on another StackOverflow thread for creating a replacement for AssetURL property from an ALAsset.
Note: See chris' comment below for more complete answer.
I like to reuse the code I write so I decided to create an extension for PHPhotoLibrary where it is possible to use it like:
PHPhotoLibrary.saveImage(photo, albumName: "Trip") { asset in
guard let asset = asset else {
assert(false, "Asset is nil")
return
}
PHPhotoLibrary.loadThumbnailFromAsset(asset) { thumbnail in
print(thumbnail)
}
}
Here is the code: https://gist.github.com/ricardopereira/636ccd0a3c8a327c43d42e7cbca4d041
As updated for Swift 2.1+ and for Video in case you are trying to do that and ended up here. Compare to the other answers for slight differences (such as using for Images rather than Video)
var photosAsset: PHFetchResult!
var collection: PHAssetCollection!
var assetCollectionPlaceholder: PHObjectPlaceholder!
//Make sure we have custom album for this app if haven't already
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %#", "MY_APP_ALBUM_NAME")
self.collection = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions).firstObject as! PHAssetCollection
//if we don't have a special album for this app yet then make one
if self.collection == nil {
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let createAlbumRequest : PHAssetCollectionChangeRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle("MY_APP_ALBUM_NAME")
self.assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection
}, completionHandler: { success, error in
if success {
let collectionFetchResult = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([self.assetCollectionPlaceholder.localIdentifier], options: nil)
print(collectionFetchResult)
self.collection = collectionFetchResult.firstObject as! PHAssetCollection
}
})
}
//save the video to Photos
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(self.VIDEO_URL_FOR_VIDEO_YOU_MADE!)
let assetPlaceholder = assetRequest!.placeholderForCreatedAsset
self.photosAsset = PHAsset.fetchAssetsInAssetCollection(self.collection, options: nil)
let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.collection, assets: self.photosAsset)
albumChangeRequest!.addAssets([assetPlaceholder!])
}, completionHandler: { success, error in
if success {
print("added video to album")
}else if error != nil{
print("handle error since couldn't save video")
}
}
})
I improved on #ricardopereira and #ColossalChris code. Added video to the extension, and added another extension on top of PHAsset to get rid of the compilation errors. Works in Swift 2.1.
Sample usage:
#import "Yourtargetname-Swift.h"//important!
NSURL *videoURL = [[NSURL alloc] initFileURLWithPath:PATH_TO_VIDEO];
[PHPhotoLibrary saveVideo:videoURL albumName:#"my album" completion:^(PHAsset * asset) {
NSLog(#"success");
NSLog(#"asset%lu",(unsigned long)asset.pixelWidth);
}];
Import both swift files:
https://github.com/kv2/PHPhotoLibrary-PhotoAsset.swift
It is usable in objective-c as long as you import the swift header for your target (see the ViewController.m file).