web-dev-qa-db-ja.com

Swift 3-ライブラリからすべての写真を取得

ライブラリから写真を取得しようとしました。うまくいきましたが、ライブラリから9枚の写真から3枚の写真を取得しました。これが私のコードです:

let options = PHFetchOptions()
    let userAlbums = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.album, subtype: PHAssetCollectionSubtype.any, options: options)

    let userPhotos = PHAsset.fetchKeyAssets(in: userAlbums.firstObject!, options: nil)
    let imageManager = PHCachingImageManager()

    userPhotos?.enumerateObjects({ (object: AnyObject!, count: Int, stop: UnsafeMutablePointer) in
        if object is PHAsset {
            let obj:PHAsset = object as! PHAsset

            let fetchOptions = PHFetchOptions()
            fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
            fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)

            let options = PHImageRequestOptions()
            options.deliveryMode = .fastFormat
            options.isSynchronous = true

            imageManager.requestImage(for: obj, targetSize: CGSize(width: obj.pixelWidth, height: obj.pixelHeight), contentMode: .aspectFill, options: options, resultHandler: { img, info in

                self.images.append(img!)
            })
        }
    })

images.count、それは3と述べた。誰かが私の間違いを見つけてすべての写真を撮るのを手伝ってくれる?本当にありがとう!

15
cathrinnatalia

これを試して、

最初に写真をインポート

import Photos

次に、viewDidLoad()の前にストア写真の配列を宣言します

var allPhotos : PHFetchResult<PHAsset>? = nil

次に、viewDidLoad()で写真を取得するためのコードを記述します

    /// Load Photos
    PHPhotoLibrary.requestAuthorization { (status) in
        switch status {
        case .authorized:
            print("Good to proceed")
            let fetchOptions = PHFetchOptions()
            self.allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions)
        case .denied, .restricted:
            print("Not allowed")
        case .notDetermined:
            print("Not determined yet")
        }
    }

次に、Arrayからの表示イメージ用にこのコードを記述します

/// Display Photo
let asset = allPhotos?.object(at: indexPath.row)
self.imageview.fetchImage(asset: asset!, contentMode: .aspectFit, targetSize: self.imageview.frame.size) 


// Or Display image in Collection View cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "photoCell", for: indexPath) as! SelectPhotoCell

    let asset = allPhotos?.object(at: indexPath.row)
    cell.imgPicture.fetchImage(asset: asset!, contentMode: .aspectFit, targetSize: cell.imgPicture.frame.size)

    return cell
}

extension UIImageView{
 func fetchImage(asset: PHAsset, contentMode: PHImageContentMode, targetSize: CGSize) {
    let options = PHImageRequestOptions()
    options.version = .original
    PHImageManager.default().requestImage(for: asset, targetSize: targetSize, contentMode: contentMode, options: options) { image, _ in
        guard let image = image else { return }
        switch contentMode {
        case .aspectFill:
            self.contentMode = .scaleAspectFill
        case .aspectFit:
            self.contentMode = .scaleAspectFit
        }
        self.image = image
    }
   }
}
19
Sapana Ranipa

Swift 5-更新

最初のインポート写真

Import Photos

すべての画像を保持する変数を作成します

var images = [UIImage]()

アセットを取得してアセットから画像をリクエストする主な機能

fileprivate func getPhotos() {

    let manager = PHImageManager.default()
    let requestOptions = PHImageRequestOptions()
    requestOptions.isSynchronous = false
    requestOptions.deliveryMode = .highQualityFormat
    // .highQualityFormat will return better quality photos
    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

    let results: PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
    if results.count > 0 {
        for i in 0..<results.count {
            let asset = results.object(at: i)
            let size = CGSize(width: 700, height: 700)
            manager.requestImage(for: asset, targetSize: size, contentMode: .aspectFill, options: requestOptions) { (image, _) in
                if let image = image {
                    self.images.append(image)
                    self.collectionView.reloadData()
                } else {
                    print("error asset to image")
                }
            }
        }
    } else {
        print("no photos to display")
    }

}
3
Toto

最初にinfo.plistで、アプリがライブラリから写真にアクセスすることを承認されていることを確認してください。以下のコードを使用してすべての写真にアクセスします。

PHPhotoLibrary.requestAuthorization { (status) in
        switch status {
        case .authorized:
            print("You Are Authrized To Access")
            let fetchOptions = PHFetchOptions()
            let allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions)
            print("Found number of:  \(allPhotos.count) images")
        case .denied, .restricted:
            print("Not allowed")
        case .notDetermined:
            print("Not determined yet")
        }
    }
1
MRizwan33