【问题标题】:Swift Select All Photos From Specific Photos AlbumSwift 从特定相册中选择所有照片
【发布时间】:2015-12-21 12:43:57
【问题描述】:

该应用程序可以在标准 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 应用如何从特定相册中收集所有图像?

【问题讨论】:

  • 您现有的代码有什么问题?
  • @jtbandes 包含的代码可以正常工作(用于收集任何相册中的所有照片),但是我只寻找特定相册的照片
  • 哪张专辑?你如何识别专辑?您的代码似乎已经在相册中获取照片,您只需选择相册即可。
  • @jtbandes 我需要它来从名为“XYZ”的某个相册中选择所有照片。目前,它只选择任何相册中的所有图像

标签: ios swift


【解决方案1】:

添加如下所示的 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)

【讨论】:

    【解决方案2】:

    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)
    
    }
    

    【讨论】:

      【解决方案3】:

      类专辑模型 { 让名称:字符串 让计数:Int 让资产:NSMutableArray 初始化(名称:字符串,计数:Int,资产:NSMutableArray){ self.name = 名称 self.count = 计数 self.asset = 资产 } } 类 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()
      }
      

      }

      类视图控制器: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)")
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-22
        • 2011-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-20
        相关资源
        最近更新 更多