UIImagePickerController 와 다르게 PHPickerViewController는 여러사진을 선택할 수 있습니다.
퍼미션 필요없구요....
PhPickerRepresentable.swift
import SwiftUI
import PhotosUI
struct PhPickerRepresentable: UIViewControllerRepresentable {
@Environment(\.presentationMode) var isPresented
@Binding var images: [UIImage]
var selectionLimit: Int
var selectedAssetIdentifiers = [String]()
var didFinishCloser: (() -> Void)?
func makeUIViewController(context: Context) -> PHPickerViewController {
var configuration = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared())
configuration.filter = .images
configuration.selectionLimit = selectionLimit
configuration.preferredAssetRepresentationMode = .current
// 사진 선택시 선택된 ICON 모양
// default: 기본 원 모양, ordered: 선택한 순서대로 숫자표시, people: ??)
if #available(iOS 15.0, *) {
configuration.selection = .ordered
configuration.preselectedAssetIdentifiers = selectedAssetIdentifiers
} else {
// Fallback on earlier versions
}
let photoPickerViewController = PHPickerViewController(configuration: configuration)
photoPickerViewController.delegate = context.coordinator
return photoPickerViewController
}
func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: PHPickerViewControllerDelegate {
private let parent: PhPickerRepresentable
init(_ parent: PhPickerRepresentable) {
self.parent = parent
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
for result in results {
if result.itemProvider.canLoadObject(ofClass: UIImage.self) {
result.itemProvider.loadObject(ofClass: UIImage.self) {[weak self] newImage, error in
guard let `self` = self else { return }
if let error = error {
print("Can't load image : \(error.localizedDescription)")
} else if let image = newImage as? UIImage {
self.parent.images.append(image)
}
}
}
}
self.parent.isPresented.wrappedValue.dismiss()
self.parent.didFinishCloser?()
}
}
}
[사용방법]
struct ContentView: View {
@State var isShowPHPicketView: Bool = false
@State var phImages: [UIImage] = []
var body: some View {
Button {
isShowPHPicketView.toggle()
} label: {
HStack {
Image(systemName: "globe")
Text("PHPicker PhotoLibary")
}
}
.modifier(GradientButtonViewModifier())
.fullScreenCover(isPresented: $isShowPHPicketView,
content: {
PhPickerRepresentable(images: $phImages, selectionLimit: 10) {
}
.ignoresSafeArea()
})
ScrollView {
ForEach(phImages, id: \.self) { uiImage in
Image(uiImage: uiImage)
.resizable()
.aspectRatio(contentMode: .fit)
}
}
}
}
'SwiftUI' 카테고리의 다른 글
[SwiftUI] Binding 변수가 옵셔널인 경우 unwrapping 해서 사용하기 (0) | 2024.06.11 |
---|---|
[SwiftUI] 조절가능한 BottomSheetView (IOS 16 미만) (0) | 2024.06.10 |
[SwiftUI] Permission Manager (0) | 2024.05.30 |
[SwiftUI] UIImagePickerController 카메라,앨범 이미지 가져오기 (0) | 2024.05.30 |
[SwiftUI] .fullScreenCover 로 NavigationView 열기 (0) | 2024.05.30 |