Hello guys I wonder how to show your selected image on PHPicker. The privacy already on selected image bur the gallery show all image. Here's some code.
Code on the view:
import SwiftUI
import PhotosUI
struct ContentView: View {
@State var isPickerShowing = false
@State var selectedImage: UIImage?
var body: some View {
VStack {
if selectedImage != nil {
Image(uiImage: selectedImage!).resizable().frame(width: 200, height: 200)
}
Button {
checkPermission()
} label: {
Text("select Photo")
}
}
.sheet(isPresented: $isPickerShowing, onDismiss: nil) {
//Image Picker
ImagePicker(imageToImport: $selectedImage, isPresented: $isPickerShowing)
}
}
func checkPermission() {
let photoAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
switch photoAuthorizationStatus {
case .authorized:
print("Access is granted by user")
isPickerShowing = true
case .notDetermined:
PHPhotoLibrary.requestAuthorization({
(newStatus) in
print("status is \(newStatus)")
if newStatus == PHAuthorizationStatus.authorized {
/* do stuff here */
isPickerShowing = true
}
})
print("It is not determined until now")
case .restricted:
// same same
print("User do not have access to photo album.")
case .denied:
// same same
print("User has denied the permission.")
case .limited:
print("User Limited Show Photo.")
@unknown default:
print("User Unknow")
}
}
}
Code on ImagePicker:
import Foundation
import PhotosUI
import SwiftUI
struct ImagePicker: UIViewControllerRepresentable {
@Binding var imageToImport: UIImage?
@Binding var isPresented: Bool
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> some UIViewController {
var configuration = PHPickerConfiguration()
configuration.filter = .images
configuration.selectionLimit = 1
let imagePicker = PHPickerViewController(configuration: configuration)
imagePicker.delegate = context.coordinator
return imagePicker
}
func updateUIViewController(_ uiViewController: ImagePicker.UIViewControllerType, context: UIViewControllerRepresentableContext<ImagePicker>) {}
func makeCoordinator() -> ImagePicker.Coordinator {
return Coordinator(parent: self)
}
class Coordinator: NSObject, PHPickerViewControllerDelegate {
var parent: ImagePicker
init(parent: ImagePicker) {
self.parent = parent
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
picker.dismiss(animated: true)
if results.count != 1 {
return
}
if let image = results.first {
if image.itemProvider.canLoadObject(ofClass: UIImage.self) {
image.itemProvider.loadObject(ofClass: UIImage.self) { image, error in
if let image = image {
self.parent.imageToImport = image as? UIImage
}
}
}
}
self.parent.isPresented.toggle()
}
}
}
Hope u guys can help me, I already search for these question for 2 weeks. Have a nice day :)