LoginSignup
5
3

More than 5 years have passed since last update.

Photos Frameworkでアルバムのサムネイルを取得する

Last updated at Posted at 2018-12-28

はじめに

photosFrameworkでユーザーアルバムのサムネイル用の画像を取得した時の内容を雑にメモしていきます。

主に使う変数

ViewController.swift
    var fetchResult: PHFetchResult<PHCollection>!
    var requestFetchResult: PHFetchResult<PHAsset>!
    var originalArray: Array! = [UIImage]()
    let imageManager = PHCachingImageManager()
    var thumbnailSize: CGSize!

ViewControllerでの記述

まずはfetchResultでアルバムを取得

ViewController.swift
override func viewDidLoad() {
        super.viewDidLoad()
        //fetchTopLevelUserCollectionsでユーザーアルバム取得
        fetchResult = PHCollectionList.fetchTopLevelUserCollections(with: nil)

        albumsTableView.dataSource = self
    }

肝となる部分

ViewController.swift
 func getThumbnail(indexPathRow: Int) {
        let collection: PHCollection
        //どのアルバムかを指定
        collection = fetchResult.object(at: indexPathRow)
        //ここでPHCollectionからPHAssetCollectionにキャスト
        guard let assetCollection = collection as? PHAssetCollection else {
            return
        }

        requestFetchResult = PHAsset.fetchAssets(in: assetCollection, options: nil)
        //アルバム内の画像が一枚もない時は適当に配列に画像を突っ込んでおく
        //ここの記述がないとindexPathが何もないというエラーを吐く
        if requestFetchResult.firstObject == nil {
            print("何もない")
            self.originalArray.append(UIImage(named: "test")!)
        } else {
            let asset = requestFetchResult.object(at: 0)


            imageManager.requestImage(for: asset, targetSize: thumbnailSize, contentMode: .aspectFill, options: nil, resultHandler: { image, _ in
                if image == nil {
                    print("managerError")
                } else {
                    self.originalArray.append(image! as UIImage)
                }
            })
        }
    }

次に

for文で配列にimageを入れていく。delegateメソッドで入れていく方が効率がいいのかわからないが、配列が空の時にcellが描画されたらめんどくさいのでviewWillAppearに記述していく。

ViewController.swift
override func viewWillAppear(_ animated: Bool) {

        let scale = UIScreen.main.scale
        let cellSize: CGFloat = (UIScreen.main.bounds.size.height / 12) - 4
        thumbnailSize = CGSize(width: cellSize * scale, height: cellSize * scale)
        for cell in 0..<fetchResult.count {
            getThumbnail(indexPathRow: cell)
            print("配列の数は\(originalArray.count)です")
        }
    }

デバックはこんな感じ

配列の数は1です
配列の数は2です
配列の数は3です
配列の数は4です
配列の数は5です
配列の数は6です
配列の数は7です
何もない
配列の数は8です
配列の数は9です
配列の数は10です
配列の数は11です
配列の数は12です
配列の数は13です
配列の数は14です
配列の数は15です
配列の数は16です

最後に

ViewController.swift
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "albumsCell", for: indexPath) as! AlbumsTableViewCell
        cell.bounds.size.width = self.albumsTableView.bounds.size.width
        //こんな感じでサムネが取得できる
        cell.albumsImage.image = originalArray[indexPath.row]

        return cell

    }
5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3