let photoAurhorizationStatus = PHPhotoLibrary.authorizationStatus()
switch photoAurhorizationStatus {
case .authorized :
print("์ ๊ทผ ํ๊ฐ๋จ")
self.requestCollection()
case .denied :
print("์ ๊ทผ ๋ถํ")
case .notDetermined:
print("์์ง ์๋ตํ์ง ์์")
PHPhotoLibrary.requestAuthorization( { (status) in
switch status {
case .authorized:
print("์ฌ์ฉ์๊ฐ ํ์ฉํจ")
self.requestCollection()
DispatchQueue.main.async {
self.collectionView.reloadData()
}
case .denied:
print("์ฌ์ฉ์๊ฐ ๋ถํํจ")
default: break
}
})
case .restricted:
print("์ ๊ทผ ์ ํ")
case .limited:
print("์ ๊ทผ ์ด์ฉ๊ตฌ")
@unknown default:
print("์ ๊ทผ ์ค๋ฅ")
}
import Photos
var fetchResult: PHFetchResult<PHAsset>!
var imageManager: PHCachingImageManager = PHCachingImageManager()
let cameraRoll: PHFetchResult<PHAssetCollection> = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil)
guard let cameraRollCollection = cameraRoll.firstObject else {
return
}
let fetchOptions = PHFetchOptions()
// ์ต์ ์์ผ๋ก ๋ถ๋ฌ์ค๋ ์ต์
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
// asset ๋ถ๋ฌ์ค๊ธฐ
self.fetchResult = PHAsset.fetchAssets(in: cameraRollCollection, options: fetchOptions)
extension PhotoLibraryViewController: UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.fetchResult?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoLibraryCell", for: indexPath) as? PhotoLibraryCell else { return UICollectionViewCell() }
let asset: PHAsset = fetchResult.object(at: indexPath.item)
imageManager.requestImage(for: asset, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFill, options: nil, resultHandler: { image, info in
cell.updateUI(image)
})
return cell
}
}
UIImagePickerController๋ฅผ ์ฌ์ฉํ์์ง๋ง ์ฌ์ง ์ฌ๋ฌ๊ฐ๋ฅผ ์ ํํ๊ณ ์ถ์ด collectionView์ asset๋ฐ์ดํฐ๋ฅผ ๋ค ๊ฐ์ ธ์ฌ ์ ์๋ PhotoKit์ผ๋ก ๋ณ๊ฒฝํด๋ณด์๋ค. PhotoKit ๊ฒ์ ์ค PHPicker๋ฅผ ๋ฐ๊ฒฌํ๋๋ฐ iOS 14์ด์๋ถํฐ ์ธ ์ ์๋๊ฒ ๋นผ๊ณค ์์ฃผ ์ธ๋งํ๊ฒ ๊ฐ์ PHPicker๋ก ๋ณ๊ฒฝํ ๊น ๊ณ ๋ฏผ์ค์ด๋ค.. ๋ด์ผ์ PHPicker์ ๋ํด ์ข ๋ ๊ณต๋ถํด๋ด์ผ๊ฒ ๋ค.