PhotosPicker 는 사진 앨범으로부터 사진이 무엇이 있는지를 보여줄 수 있는 View 입니다.

 

Photos picker 를 사용하게 되면 앨범으로부터 영상 또는 사진을 뷰를 통해 탐색할 수 있습니다.  뷰는 하나 또는 여러개의 선택을 할 수 있는 메서드가 존재합니다. 아래 예시에서는 버튼을 눌렀을 때 picker 뷰에서 여러 개를 선택할 수 있는 모드가 됩니다.

import SwiftUI
import PhotosUI


struct PhotosSelector: View {
    @State var selectedItems: [PhotosPickerItem] = []


    var body: some View {
        PhotosPicker(selection: $selectedItems,
                     matching: .images) {
            Text("Select Multiple Photos")
        }
    }
}

 

picker 뷰를 보여줄 때 PHPickerFilter 옵션을 사용하여 뷰를 통해 사용자한테 보여줄 것을 커스텀화 할 수 있습니다. 다음 예시처럼 사진들과 스크린샷을 동시에 보여줄 수 있습니다.

PhotosPicker(selection: $selectedItems,
             matching: .any(of: [.images, .not(.screenshots)])) {
    Text("Select Photos")
}

 

selection으로 얻는 값은 placeholder 객체입니다. PhotosPickerItemTransferable을 준수하며, 요청한 표현을 불러올 수 있습니다. SwiftUI 이미지를 불러오고 진행 상황을 파악하려면 loadTransferable(type:completionHandler:)을 사용해야합니다.

 

loadTransferable(type: _, completionHandler:_ ) 를 사용하면 원하는 type으로 PhotosPickerItem를  result 로 반환하여 사용할 수 있게 됩니다. completionHandler 에서 result는 Transferable 를 준수하기 때문에 데이터 전송이 완료됐는지를 확인할 수 있습니다.

func loadTransferable(from imageSelection: PhotosPickerItem) -> Progress {
    return imageSelection.loadTransferable(type: Image.self) { result in
        DispatchQueue.main.async {
            guard imageSelection == self.imageSelection else { return }
            switch result {
            case .success(let image?):
                // Handle the success case with the image.
            case .success(nil):
                // Handle the success case with an empty value.
            case .failure(let error):
                // Handle the failure case with the provided error.
            }
        }
    }
}

 

iCloud 사진들을 네트워크 연결이 보장되지 않았을 때 처럼 시스템이 데이터를 불러올 때 에러가 발생할 수 있습니다.

'SwiftUI' 카테고리의 다른 글

RotateGesture  (0) 2024.01.06
Transferable  (0) 2023.12.22
Shapes ( Rectangle, RoundedRectangle, Circle, Ellipse, Capsule ...)  (0) 2023.12.20
PreferenceKey Protocol  (0) 2023.12.19
GeometryReader  (0) 2023.12.19
ytw_developer