【发布时间】:2020-09-24 11:20:09
【问题描述】:
在我的 SwiftUI 项目中,我需要使用要在项目的其他部分重用的图像 url。
我创建了这个图像选择器,它允许我在手机相册或使用 iPhone 相机拍摄新照片之间进行选择(使用 var shootNew: Bool)
我面临以下问题:当我使用选择器从相册中选择图像时,我正在获取图像的 url,但是当我想用相机拍摄新照片时,我无法获取 url新图片,
如何获取用相机拍摄的图片的url?
这里是我的图片选择器
struct ImagePickerNew: UIViewControllerRepresentable {
var shootNew: Bool
var needEdit: Bool
@Binding var image: UIImage?
@Binding var isPresented: Bool
@Binding var imageUrl : URL?
class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
var shootNew: Bool
var needEdit: Bool
@Binding var image: UIImage?
@Binding var isPresented: Bool
@Binding var imageUrl : URL?
init(shootNew: Bool, needEdit: Bool, image: Binding<UIImage?>, isPresented:Binding<Bool>, imageURL1 : Binding<URL?>) {
self.shootNew = shootNew
self.needEdit = needEdit
_image = image
_isPresented = isPresented
_imageUrl = imageURL1
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let imageEdited = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
self.image = imageEdited
} else {
self.image = (info[UIImagePickerController.InfoKey.originalImage] as! UIImage)
}
if let imageURLEdited = info[UIImagePickerController.InfoKey.imageURL] as? URL{
self.imageUrl = imageURLEdited
debugPrint("ho url")
} else {
debugPrint("UNABLE URL")
}
self.isPresented = false
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.isPresented = false
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(shootNew: shootNew, needEdit: needEdit, image: $image, isPresented: $isPresented, imageURL1: $imageUrl)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePickerNew>) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
picker.navigationController?.delegate = context.coordinator
picker.sourceType = shootNew ? .camera : .photoLibrary
picker.allowsEditing = needEdit
picker.mediaTypes = [kUTTypeImage] as [String]
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController,
context: UIViewControllerRepresentableContext<ImagePickerNew>) {
}
}
非常感谢你帮助我。
【问题讨论】:
标签: ios swift url swiftui uiimagepickercontroller