-
Notifications
You must be signed in to change notification settings - Fork 0
PhotoLibrary
이 메소드는 iOS3.x나 이전버전에서는 사용자가 앱을 종료하면 언제나 호출된다. 백그라운드 실행을 지원하는 앱의 경우, 앱이 단순히 백그라운드로 이동하기 때문에 사용자가 앱을 종료 할 때 이 메소드는 일반적으로 호출되지 않는다. 하지만 이 메소드는 앱이 백그라운드에서 실행 중이고(not suspended) 시스템이 어떠한 이유로 앱을 종료하면 호출된다.
이 메소드를 호출하고 나서, 관심있는 객체에게 전환에 응답할 수 있는 기회를 주기위해 앱은 willTerminateNotification
notification을 발송한다.
두가지 역할을 다 해야한다.
-
PHFetchResult<PHAsset>
-
PHFetchResult.object(at:)
-
PHCachingImageManager()
-
PHPhotoLibrary
먼저 PHFetchResult<PHAsset>
타입의 프로퍼티인 fetchResult
를 선언해준다.
이 변수에는 PHAsset의 fetchAsset 메소드가 반환하는 값이들어간다.
(클래스 세부 설명 생략)
fetchResult = PHAsset.fetchAssets(with: nil)
원래는 fetchAssets
메소드 호출을 collectionViewController가 있는 곳에서 보통 구현하는데, 현재는 dataSource 구현을 분리했으므로 dataSource에 fetchResult
를 만들었다.
PHFetchResult
Generic Class 타입인 fetchResult
에서 Asset을 하나씩 꺼내와야한다.
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)
fileprivate let imageManager = PHCachingImageManager()
imageManager
는 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
}
}
A shared object that manages access and changes to the user’s shared photo library.
요구사항은 위의 옵저버를 구현하는 것.
Register an observer to be notified of changes to the photo library
아래 글은 PHPhotoLibrary
에 대한 변경을 요청할 수 있는데, 옵저버는 이를 관찰한다.
프로토콜, PHPhotoLibraryChangeObserver
이 있는데 이 옵저버가 PHPhotoLibrary
에 대한 변경 notification을 받기 위해서 이를 처음에 등록해줘야한다.
보통 뷰컨트롤러에서 뷰컨트롤러 자신을 등록한다.
PHPhotoLibrary.shared().register(self)
등록 이후 변경된 사항은 아래 stub에서 구현한다.
func photoLibraryDidChange(_ changeInstance: PHChange)
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.
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
private let datasource = CollectionViewDataSource(count: 40)
private var size: CGSize = CGSize(width: 80, height: 80)
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = datasource
collectionView.delegate = self
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return size
}
UICollectionViewDelegateFlowLayout
는 UICollectionViewDelegate
를 상속한다.
{: .notice--warning}
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()