Last active
October 20, 2020 15:40
-
-
Save feveral/30dacd21e292ac81f92eeb208b699d72 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import Photos | |
public struct ImagePicker: UIViewControllerRepresentable { | |
private let sourceType: UIImagePickerController.SourceType | |
private let onImagePicked: (Data) -> Void | |
@Environment(\.presentationMode) private var presentationMode | |
init(sourceType: UIImagePickerController.SourceType, onImagePicked: @escaping (Data) -> Void) { | |
self.sourceType = sourceType | |
self.onImagePicked = onImagePicked | |
} | |
public func makeUIViewController(context: Context) -> UIImagePickerController { | |
let picker = UIImagePickerController() | |
picker.sourceType = self.sourceType | |
picker.delegate = context.coordinator | |
return picker | |
} | |
public func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {} | |
public func makeCoordinator() -> Coordinator { | |
Coordinator( | |
onDismiss: { self.presentationMode.wrappedValue.dismiss() }, | |
onImagePicked: self.onImagePicked | |
) | |
} | |
final public class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate { | |
private let onDismiss: () -> Void | |
private let onImagePicked: (Data) -> Void | |
init(onDismiss: @escaping () -> Void, onImagePicked: @escaping (Data) -> Void) { | |
self.onDismiss = onDismiss | |
self.onImagePicked = onImagePicked | |
} | |
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { | |
// get permission from user | |
let status = PHPhotoLibrary.authorizationStatus() | |
if status == .notDetermined { | |
PHPhotoLibrary.requestAuthorization({status in}) | |
} | |
// get image PHAsset | |
guard let asset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset else { | |
print("error: user permission not open!") | |
return | |
} | |
let imageManager = PHImageManager.default() | |
imageManager.requestImageDataAndOrientation(for: asset, options: nil) { data, _, _, _ in | |
if let data = data, let uiImage = info[.originalImage] as? UIImage { | |
// get your image data and uiimage | |
self.onImagePicked(uiImage.jpegData(compressionQuality: 1)!) | |
} else { | |
print("error: get image failed") | |
} | |
} | |
self.onDismiss() | |
} | |
public func imagePickerControllerDidCancel(_: UIImagePickerController) { | |
self.onDismiss() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment