Swift Select All Photos From Specific Photos Album
Add fetchOptions like below
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", YourAlbumTitle)
let resultCollections = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .AlbumRegular, options: fetchOptions)
Actually, the album title isn't a unique value, they can be duplicated. so I recommend using localIdentifier like below if your app access multiple albums.
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "localIdentifier = %@", YourAlbumLocalIdentifier)
let resultCollections = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .AlbumRegular, options: fetchOptions)
How to fetch all images from custom Photo Album - Swift
For Swift 4
using this answer https://stackoverflow.com/a/28904792/4795651 edited a little for myself.
import Photos
func fetchCustomAlbumPhotos()
{
let albumName = "Album Name Here"
var assetCollection = PHAssetCollection()
var albumFound = Bool()
var photoAssets = PHFetchResult<AnyObject>()
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)
let collection:PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
if let firstObject = collection.firstObject{
//found the album
assetCollection = firstObject
albumFound = true
}
else { albumFound = false }
_ = collection.count
photoAssets = PHAsset.fetchAssets(in: assetCollection, options: nil) as! PHFetchResult<AnyObject>
let imageManager = PHCachingImageManager()
photoAssets.enumerateObjects{(object: AnyObject!,
count: Int,
stop: UnsafeMutablePointer<ObjCBool>) in
if object is PHAsset{
let asset = object as! PHAsset
print("Inside If object is PHAsset, This is number 1")
let imageSize = CGSize(width: asset.pixelWidth,
height: asset.pixelHeight)
/* For faster performance, and maybe degraded image */
let options = PHImageRequestOptions()
options.deliveryMode = .fastFormat
options.isSynchronous = true
imageManager.requestImage(for: asset,
targetSize: imageSize,
contentMode: .aspectFill,
options: options,
resultHandler: {
(image, info) -> Void in
self.photo = image!
/* The image is now available to us */
self.addImgToArray(uploadImage: self.photo!)
print("enum for image, This is number 2")
})
}
}
}
func addImgToArray(uploadImage:UIImage)
{
self.images.append(uploadImage)
}
For Swift 2.1
import Photos
func FetchCustomAlbumPhotos()
{
var albumName = "SwiftAlbum"
var assetCollection = PHAssetCollection()
var albumFound = Bool()
var photoAssets = PHFetchResult()
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)
let collection:PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions)
if let first_Obj:AnyObject = collection.firstObject{
//found the album
assetCollection = collection.firstObject as! PHAssetCollection
albumFound = true
}
else { albumFound = false }
var i = collection.count
photoAssets = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: nil)
let imageManager = PHCachingImageManager()
// let imageManager = PHImageManager.defaultManager()
photoAssets.enumerateObjectsUsingBlock{(object: AnyObject!,
count: Int,
stop: UnsafeMutablePointer<ObjCBool>) in
if object is PHAsset{
let asset = object as! PHAsset
print("Inside If object is PHAsset, This is number 1")
let imageSize = CGSize(width: asset.pixelWidth,
height: asset.pixelHeight)
/* For faster performance, and maybe degraded image */
let options = PHImageRequestOptions()
options.deliveryMode = .FastFormat
options.synchronous = true
imageManager.requestImageForAsset(asset,
targetSize: imageSize,
contentMode: .AspectFill,
options: options,
resultHandler: {
(image, info) -> Void in
self.photo = image!
/* The image is now available to us */
self.addImgToArray(self.photo)
print("enum for image, This is number 2")
})
}
}
}
func addImgToArray(uploadImage:UIImage)
{
self.images.append(uploadImage)
}
List all photo albums in iOS
I use this to get just a few albums but you can get more:
private func setupPhotos() {
let fetchOptions = PHFetchOptions()
let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .any, options: fetchOptions)
let topLevelUserCollections = PHCollectionList.fetchTopLevelUserCollections(with: fetchOptions)
let allAlbums = [topLevelUserCollections, smartAlbums]
allAlbums.enumerateObjects {(assetCollection, index, stop) in
if #available(iOS 9.0, *) {
fetchOptions.fetchLimit = 1
}
let assets = PHAsset.fetchAssets(in: assetCollection, options: fetchOptions)
if let _ = assets.firstObject {
let assetObject = MYSpecialAssetContainerStruct(asset: assets)
self.myDataArray.append(assetObject)
}
}
self.myDataArray.sortInPlace {(a, b) in
return a.asset.localizedTitle < b.asset.localizedTitle
}
tableView.reloadData()
}
EDIT: This will get you the PHAssetCollections
of the albums, then I put them in cells which have this method for getting the latest image thumbnail from the album.
private func downloadAndSetImage(asset: MYSpecialAssetContainerStruct) {
guard asset.thumbnail == nil else {
albumImage.image = asset.thumbnail
return
}
let imageRequestOptions = PHImageRequestOptions()
imageRequestOptions.isNetworkAccessAllowed = false
imageRequestOptions.isSynchronous = true
imageRequestOptions.deliveryMode = .highQualityFormat
PHImageManager.default().requestImage(
for: asset.asset,
targetSize: CGSize(width: 200, height: 200),
contentMode: .aspectFit,
options: imageRequestOptions,
resultHandler: {(img, info) in
asset.thumbnail = img
self.albumImage.image = asset.thumbnail
}
)
}
How to fetch Photos album title & count in swift?
You can use Photos
framework with fetchAssetCollections
Don't forget to adda Privacy - Photo Library Usage Description
Key in your info.plist
import Photos
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let albumsPhoto:PHFetchResult<PHAssetCollection> = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil)
albumsPhoto.enumerateObjects({(collection, index, object) in
let photoInAlbum = PHAsset.fetchAssets(in: collection, options: nil)
print(photoInAlbum.count)
print(collection.localizedTitle)
})
}
}
How to fetch photos album title, image count in swift?
The minimum number of steps to achieve what you are asking is:
// import the framework
import Photos
// get the albums list
let albumList = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil)
// you can access the number of albums with
albumList.count
// individual objects with
let album = albumList.object(at: 0)
// eg. get the name of the album
album.localizedTitle
// get the assets in a collection
func getAssets(fromCollection collection: PHAssetCollection) -> PHFetchResult<PHAsset> {
let photosOptions = PHFetchOptions()
photosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
photosOptions.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.image.rawValue)
return PHAsset.fetchAssets(in: collection, options: photosOptions)
}
// eg.
albumList.enumerateObjects { (coll, _, _) in
let result = self.getAssets(fromCollection: coll)
print("\(coll.localizedTitle): \(result.count)")
}
// Now you can:
// access the count of assets in the PHFetchResult
result.count
// get an asset (eg. in a UITableView)
let asset = result.object(at: indexPath.row)
// get the "real" image
PHCachingImageManager.default().requestImage(for: asset, targetSize: CGSize(width: 200, height: 200), contentMode: .aspectFill, options: nil) { (image, _) in
// do something with the image
}
I also suggest to take a look at the Apple sample code for the Photos framework, is not hard to follow, together with the Photos framework documentation.
Swift - How get photo albums with all photos include iCloud Library?
I change fetch and all working.
Old code:
if let result = PHAsset.fetchKeyAssets(in: collection, options: onlyImagesOptions){
//Code
}
New code
let result = PHAsset.fetchAssets(in: collection, options: onlyImagesOptions)
How to select multiple videos from album in swift?
If you want to use picker to select multiple videos from gallery, use this pod.
https://github.com/opalorange/OpalImagePicker
Related Topics
Handle Multiple File (Image) Uploads to Aws S3 Swift
iOS Keyboard Active But Invisible When Uisearchbar Is Tapped
Didbegincontact Passed Pkphyicsobject
What Are the First Two Columns in Scnmatrix4
Swift: Memory Not Clearing When I Segue to Another View Controller, Recieving Memory Warning
Periodically Call an API with Rxswift
Avmutablecomposition Resizing Issue
Hls Metadata Id3 Tag Not Working
Uisearchbar Out of Screen Bounds When Navigation Bar Translucent = False
How to Perform Realm Count Query
Do I Need to Wrap My Alamofire Calls Inside Dispatch_Async
Segue Out of Navigation Controller
Customise Uitabbar Height in Xcode11/Ios13 or 13.1