iOS, PhotoKit(사진가져오기)
🧐 사진(Photos)에서 사진들을 가져오는 것을 단계별로 한번 알아보겠습니다!
Step 1
Info.plist 설정해주세요!

Step 2
Photos를 import하고 PHAsset를 받을 프로퍼티와 추가해주세요.
🍁 PHAsset
사진 라이브러리에 있는 image, video, or Live Photo에 대한 메타데이터입니다.
🍁 PHFetchResult
fetch 메소드를 통해 가져오기 위한 asset 컬렉션입니다.
🍁 ViewController.swift
import Photos
class ViewController: UIViewController {
    var photos: PHFetchResult<PHAsset>?
    ...
}
Step 3
이제 asset들을 가져올 차례입니다. 저 같은 경우는 접근 권한이 허용할 경우 가져와 collection view를 reload하기 위해 accessPhotos() 메소드를 생성했습니다.
🍁 fetchAssets(in assetCollection: options:)
asset들을 가져오는 메소드입니다. 리턴 값은 PHFetchResult 입니다.
🍁 ViewController.swift
class ViewController: UIViewController {
  
    ...
  
    func accessPhotos() {
        PHPhotoLibrary.requestAuthorization { [weak self] status in
            if status == .authorized {
                self?.photos = PHAsset.fetchAssets(with: nil)
                DispatchQueue.main.async {
                    self?.collectionView.reloadData()
                }
            }
        }
    }
}
Step 4
이미지를 업데이트 시켜줘야할 차례입니다. PHAsset는 그져 데이터이므로, 데이터를 가지고 PHImageManager를 사용하여 이미지를 요청해야합니다. PHImageManager 프로퍼티를 생성하고 cellForItemAt에서 사용합시다.
🍁 PHImageManager
미리보기 썸네일 및 asset 데이터 검색 또는 생성을 용이하게 하는 개체입니다.
🍁 ViewController.swift
class ViewController: UIViewController { 
    ...
  
    let imageManager = PHImageManager()
  
    ...
}
extension ViewController: UICollectionViewDataSource {
    
    ...
  
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? Cell else {
            return UICollectionViewCell()
        }
        
        let asset = photos?[indexPath.item]
        cell.representedAssetIdentifier = asset?.localIdentifier
        imageManager.requestImage(for: asset!, targetSize: imageSize, contentMode: .default, options: nil) { image, _ in
            if cell.representedAssetIdentifier == asset?.localIdentifier {
                cell.image.image = image
            }
        }
        return cell
    }
}
🧐(아래 참고내용을 통해 더 자세한 정보를 확인할 수 있습니다!)
Apple Developer Documentation
Author And Source
이 문제에 관하여(iOS, PhotoKit(사진가져오기)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@idoyoung/iOS-PhotoKit사진가져오기저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)