import SwiftUI
import PhotosUI
import UniformTypeIdentifiers
import UIKit
// MARK: - Usage Example
struct ContentView: View {
@State private var showSourceSelection = false
@State private var showDocumentPicker = false
@State private var showCameraPicker = false
@State private var showGalleryPicker = false
@State private var selectedImage: UIImage?
@State private var selectedImages: [UIImage] = []
private let config = MediaPickerConfig()
var body: some View {
VStack(spacing: 20) {
if let image = selectedImage {
Image(uiImage: image)
.resizable()
.scaledToFit()
.frame(maxWidth: 300, maxHeight: 300)
}
Button("Select Media") {
let helper = UnifiedMediaPickerHelper(config: config, onMediaPicked: { _ in }, onCancel: nil)
if helper.shouldShowSourceSelection() {
showSourceSelection = true
} else if let pickerType = helper.getDirectPickerType() {
switch pickerType {
case .document: showDocumentPicker = true
case .camera: showCameraPicker = true
case .gallery: showGalleryPicker = true
}
}
}
}
.confirmationDialog("Select Source", isPresented: $showSourceSelection, titleVisibility: .visible) {
Button("Camera") {
showCameraPicker = true
}
Button("Photo Gallery") {
showGalleryPicker = true
}
Button("Cancel", role: .cancel) {}
}
.fullScreenCover(isPresented: $showCameraPicker) {
CameraPicker(
allowsVideo: config.allowVideos,
onImagePicked: { images, urls in
handleImagePicked(images: images, urls: urls, fromCamera: true)
},
onVideoPicked: { url in
// Handle video selection
showCameraPicker = false
},
onCancel: {
showCameraPicker = false
}
)
}
.sheet(isPresented: $showGalleryPicker) {
ImagePicker(
allowsMultipleSelection: config.allowMultipleSelection,
maxSelectionCount: config.maxSelectionCount,
allowsVideos: config.allowVideos,
onImagePicked: { images, urls in
handleImagePicked(images: images, urls: urls, fromCamera: false)
},
onVideoPicked: { urls in
// Handle video selection
showGalleryPicker = false
}
)
}
}
private func handleImagePicked(images: [UIImage], urls: [URL]?, fromCamera: Bool) {
selectedImage = images.first
showCameraPicker = false
showGalleryPicker = false
}
}
// Note: Add to Info.plist:
// <key>NSPhotoLibraryUsageDescription</key>
// <string>We need access to your photo library</string>
// <key>NSCameraUsageDescription</key>
// <string>We need access to your camera</string>