Skip to content

PhotoLibrary

Dongjun Kim edited this page Mar 17, 2020 · 2 revisions
  1. PHFetchResult<PHAsset>

  2. PHFetchResult.object(at:)

  3. PHCachingImageManager()

  4. PHPhotoLibrary


1. PHFetchResult<PHAsset>

먼저 PHFetchResult<PHAsset> 타입의 프로퍼티인 fetchResult를 선언해준다.

이 변수에는 PHAsset의 fetchAsset 메소드가 반환하는 값이들어간다.

(클래스 세부 설명 생략)

fetchResult = PHAsset.fetchAssets(with: nil)

원래는 fetchAssets 메소드 호출을 collectionViewController가 있는 곳에서 보통 구현하는데, 현재는 dataSource 구현을 분리했으므로 dataSource에 fetchResult를 만들었다.


2. PHFetchResult.object(at:)

PHFetchResult Generic Class 타입인 fetchResult에서 Asset을 하나씩 꺼내와야한다.

object(at:)

Returns the object located at the specified index.

이때 collectionView의 index에 맞추어 꺼내올 수 있는 메소드가 있다.

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhotoCell.CELL_IDENTIFIER, for: indexPath) as! PhotoCell
        let asset = fetchResult.object(at: indexPath.item)

3. PHCachingImageManager()

fileprivate let imageManager = PHCachingImageManager()

imageManagerPHCachingImageManager의 인스턴스로 썸네일 이미지를 만드는데 사용된다.

PHCachingImageManager

An object that facilitates retrieving or generating preview thumbnails, optimized for batch preloading large numbers of assets.

imageManager.requestImage(for: asset, targetSize: thumbnailSize, contentMode: .default, options: nil) { (image, _) in
            cell.thumbnailImage = image
        }

여기서 didSet을 활용하여 Image를 받으면 디미터 법칙도 지킬 수 있고, 더 깔끔하다.

var thumbnailImage: UIImage! {
        didSet {
            imageView.image = thumbnailImage
        }
    }

4. PHPhotoLibrary

A shared object that manages access and changes to the user’s shared photo library.

Observing Changes in the Photo Library

요구사항은 위의 옵저버를 구현하는 것.

Register an observer to be notified of changes to the photo library

아래 글은 PHPhotoLibrary에 대한 변경을 요청할 수 있는데, 옵저버는 이를 관찰한다.

PhotoKit 간단 사용법 - 변경 요청하기

프로토콜, PHPhotoLibraryChangeObserver이 있는데 이 옵저버가 PHPhotoLibrary에 대한 변경 notification을 받기 위해서 이를 처음에 등록해줘야한다.

보통 뷰컨트롤러에서 뷰컨트롤러 자신을 등록한다.

PHPhotoLibrary.shared().register(self)

등록 이후 변경된 사항은 아래 stub에서 구현한다.

func photoLibraryDidChange(_ changeInstance: PHChange)

Handling Changes: An Example

The view controller keeps a reference to the PHAssetCollection object representing the displayed album and the PHFetchResult object (returned by the fetchAssets(in:options:) method) listing the album’s contents. Then, in its photoLibraryDidChange(_:) method, the view controller checks for differences between the objects it fetched and the new state of the photo library, and updates its collection view accordingly.


collectionview sizeforitemat not working with iamgeView

A: Set collectionView's Estimated Size to .None

You set collectionview Estimate size to None in Xcode 11. The reason for this is that cells in a UICollectionView can now self-size with Auto Layout constrained views in the canvas. To opt into the behavior for existing collection views, enable “Automatic” for the collection view’s estimated size, and “Automatic” for cell’s size from the Size inspector.

If deploying before iOS 13, you can activate self sizing collection view cells by calling performBatchUpdates(_:completion:) during viewDidLoad()