iOS8 Photos Framework: How to get the name(or filename) of a PHAsset?
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)
}
}
}
})
}
}
Get File Extension from a PHAsset in iOS 8?
File names are an implementation detail, and may or may not tell you what the content of a file really is.
When you call requestImageDataForAsset
, the dataUTI
parameter that Photos passes to your completion handler tells you the Uniform Type Identifier for the image data.
PHAsset get original file name
On iOS 8 your solution is the right (and only approach) to get a filename at all.
On iOS 9 this works:
NSArray *resources = [PHAssetResource assetResourcesForAsset:asset];
NSString *orgFilename = ((PHAssetResource*)resources[0]).originalFilename;
iOS8 Photos Framework: How to get the name(or filename) of a PHAsset?
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)
}
}
}
})
}
}
iOS Photos library - how to get the REAL filename?
I figured it out.
let resources = PHAssetResource.assetResources(for: asset)
print("Filename: \((resources.first as! PHAssetResource).originalFilename)")
iOS 8 Photos framework: Get a list of all albums with iOS8
Using Photos Framework is a bit different, you can achieve the same result though, you just have to do it in parts.
1) Get all photos (Moments in iOS8, or Camera Roll before)
PHFetchResult *allPhotosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];
Optionally if you want them ordered as by creation date, you just add PHFetchOptions
like so:
PHFetchOptions *allPhotosOptions = [PHFetchOptions new];
allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
PHFetchResult *allPhotosResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:allPhotosOptions];
Now if you want you can get assets from the PHFetchResult
object:
[allPhotosResult enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
NSLog(@"asset %@", asset);
}];
2) Get all user albums (with additional sort for example to only show albums with at least one photo)
PHFetchOptions *userAlbumsOptions = [PHFetchOptions new];
userAlbumsOptions.predicate = [NSPredicate predicateWithFormat:@"estimatedAssetCount > 0"];
PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:userAlbumsOptions];
[userAlbums enumerateObjectsUsingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL *stop) {
NSLog(@"album title %@", collection.localizedTitle);
}];
For each PHAssetCollection
that is returned from PHFetchResult *userAlbums
you can fetch PHAssets
like so (you can even limit results to include only photo assets):
PHFetchOptions *onlyImagesOptions = [PHFetchOptions new];
onlyImagesOptions.predicate = [NSPredicate predicateWithFormat:@"mediaType = %i", PHAssetMediaTypeImage];
PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:collection options:onlyImagesOptions];
3) Get smart albums
PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
[smartAlbums enumerateObjectsUsingBlock:^(PHAssetCollection *collection, NSUInteger idx, BOOL *stop) {
NSLog(@"album title %@", collection.localizedTitle);
}];
One thing to note with Smart Albums is that collection.estimatedAssetCount
can return NSNotFound
if estimatedAssetCount cannot be determined. As title suggest this is estimated. If you want to be sure of number of assets you have to perform fetch and get the count like:
PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
number of assets = assetsFetchResult.count
Apple has a sample project that does what you want:
https://developer.apple.com/library/content/samplecode/UsingPhotosFramework/ExampleappusingPhotosframework.zip (you have to be a registered developer to access this)
NSURL from PHAsset
If you use [imageManager
requestAVAssetForVideo
...], it'll return an AVAsset
. That AVAsset is actually an AVURLAsset
, so if you cast it, you can access it's -url
property.
I'm not sure if you can create a new asset out of this, but it does give you the location.
Related Topics
How to Center Align the Cells of a Uicollectionview
How to Implement Lazy Loading of Images in Table View Using Swift
iOS Nsdate() Returns Incorrect Time
iOS 9 Safari: Changing an Element to Fixed Position While Scrolling Won't Paint Until Scroll Stops
How to Get Touches When Parent View Has Userinteractionenabled Set to No in iOS
Generate Random Numbers with a Given Distribution
Where to Store Global Constants in an iOS Application
Uitableviewcell with Autolayout Left Margin Different on iPhone and iPad
iPhone - Draw Transparent Rectangle on Uiview to Reveal View Beneath
How to Store an Image in Core Data
Simple and Clean Way to Convert JSON String to Object in Swift
How to Password Protect Writing to Nfc Ntag216 Tag on iOS 13 Using Nfc Core
What Are the Device-Width CSS Viewport Sizes of the Iphone6 and iPhone 6 Plus
When Should I Use the Various Storage Mechanisms in iOS