I tried to show only photo that I selected before, but it won't work and show all photos. How do I solve this issue? I tried to use permission to limited access but it end up showing all of the photos - not just the photo I selected.
Photos show image
Permission selected image
This is my View
's code:
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(selectedImage: $selectedImage, isPickerShowing: $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")
}
}
}
here my ImagePicker:
struct ImagePicker: UIViewControllerRepresentable {
@Binding var selectedImage: UIImage?
@Binding var isPickerShowing: Bool
func makeUIViewController(context: Context) -> some UIViewController {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = context.coordinator
return imagePicker
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {}
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
}
class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var parent: ImagePicker
init(_ picker: ImagePicker) {
self.parent = picker
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
DispatchQueue.main.async {
self.parent.selectedImage = image
}
}
self.parent.isPickerShowing = false
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.parent.isPickerShowing = false
}
}
I aim to only show the selected image.