该应用可以在标准的iOS照片应用程序中创建自定义相册,但我无法找到应用程序收集该相册中的所有图像以便在应用程序中显示的方法。
目前,该应用程序可以从所有相册中收集图像,而不是特别的。
let resultCollections = PHAssetCollection.fetchAssetCollectionsWithType(
.Album,
subtype: .AlbumRegular,
options: nil)
resultCollections.enumerateObjectsUsingBlock({
(object, index, stop) -> Void in
let collection = object as! PHAssetCollection
let result = PHAsset.fetchAssetsInAssetCollection(collection, options: nil)
result.enumerateObjectsUsingBlock({
(object, index, stop) -> Void in
let asset = object as! PHAsset
self.images.append(asset)
})
})
我已经看到其他可能被标记为重复的问题,但是大多数问题都在讨论将UIPickerView打开到自定义相册。这可能是How to fetch all images from custom Photo Album - swift的副本,但是从未回答过。
那么,iOS应用程序如何收集特定相册中的所有图像?
答案 0 :(得分:7)
添加如下所示的fetchOptions
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", YourAlbumTitle)
let resultCollections = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .AlbumRegular, options: fetchOptions)
实际上,专辑标题不是唯一值,它们可以复制。所以如果您的应用访问多个相册,我建议使用如下所示的localIdentifier。
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "localIdentifier = %@", YourAlbumLocalIdentifier)
let resultCollections = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .AlbumRegular, options: fetchOptions)
答案 1 :(得分:7)
Swift 4的工作代码
我的回答可能会帮助您和其他人(https://stackoverflow.com/a/35178022/4795651),但此后也会在此处添加代码.. !!
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)
}
对于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)
}
答案 2 :(得分:1)
class AlbumModel { 让name:String 让计数:Int let asset:NSMutableArray init(name:String,count:Int,asset:NSMutableArray){ self.name = name self.count = count self.asset = asset } } class yourCustomCell:UITableViewCell {
//MARK:- Properties
@IBOutlet weak var collectionView: UICollectionView!
//MARK:- initialization methods
override func awakeFromNib() {
super.awakeFromNib()
// setupView()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
//MARK:- Setup collectionView datasource and delegate
func setCollectionViewDataSourceDelegate<T:UICollectionViewDataSource & UICollectionViewDelegate>(dataSourceDelegate: T, forRow row: Int) {
collectionView.delegate = dataSourceDelegate
collectionView.dataSource = dataSourceDelegate
collectionView.tag = row
collectionView.reloadData()
}
}
类ViewController:UIViewController {
var tablearray = NSMutableArray()
func getAssetThumbnail(asset: PHAsset) -> UIImage {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
var thumbnail = UIImage()
option.isSynchronous = true
manager.requestImage(for: asset, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in
thumbnail = result!
})
return thumbnail
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//print(UnladenSwallow.unknown)
let fetchOptions = PHFetchOptions()
let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .any, options: fetchOptions)
let topLevelfetchOptions = PHFetchOptions()
let topLevelUserCollections = PHCollectionList.fetchTopLevelUserCollections(with: topLevelfetchOptions)
let allAlbums = [topLevelUserCollections, smartAlbums]
var name = ""
smartAlbums.enumerateObjects({
if let collection = $0.0 as? PHAssetCollection{
name = collection.localizedTitle!
let image_arry = NSMutableArray()
let result = PHAsset.fetchAssets(in: collection, options: nil)
result.enumerateObjects({ (object, index, stop) -> Void in
let asset = object
image_arry.add(self.getAssetThumbnail(asset: asset))
})
let newAlbum = AlbumModel(name: name, count: collection.estimatedAssetCount, asset:image_arry)
self.tablearray.add(newAlbum)
}
})
topLevelUserCollections.enumerateObjects({
if let collection = $0.0 as? PHAssetCollection{
name = collection.localizedTitle!
let image_arry = NSMutableArray()
let result = PHAsset.fetchAssets(in: collection, options: nil)
result.enumerateObjects({ (object, index, stop) -> Void in
let asset = object
image_arry.add(self.getAssetThumbnail(asset: asset))
})
let newAlbum = AlbumModel(name: name, count: collection.estimatedAssetCount, asset:image_arry)
self.tablearray.add(newAlbum)
}
})
print(self.tablearray)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
扩展名ViewController:UITableViewDataSource,UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int{
return self.tablearray.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let album = self.tablearray[section] as! AlbumModel
return album.name
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! yourCustomCell
cell.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, forRow: indexPath.section)
return cell
}
} 扩展ViewController:UICollectionViewDelegate,UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let album = self.tablearray[collectionView.tag] as! AlbumModel
print("count = \(album.asset.count)")
return album.asset.count;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let album = self.tablearray[collectionView.tag] as! AlbumModel
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "col", for: indexPath)
let img = cell.viewWithTag(111) as! UIImageView
img.image = album.asset.object(at: indexPath.row) as? UIImage
return cell
}
}
func collectionView(collectionView:UICollectionView,didSelectItemAtIndexPath indexPath:IndexPath){
print("get selected collectionview itemindex \(indexPath.row)")
}