我的 ImagePicker 按预期工作。但是,我正在尝试实现相机权限处理,但我似乎陷入了困境。我收到错误:“函数中缺少返回预期返回 UIImagePickerController”,这是理所当然的。我不确定还能在哪里放置 switch 语句来执行处理。任何帮助表示赞赏。
struct ImagePicker: UIViewControllerRepresentable {
var sourceType: UIImagePickerController.SourceType = .photoLibrary
@Binding var selectedImage: UIImage
@Binding var alertCameraAccessNeeded: Bool
@Environment(\.presentationMode) private var presentationMode
@EnvironmentObject private var userManager: UserManager
let cameraAuthStatus = AVCaptureDevice.authorizationStatus(for: .video)
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
switch cameraAuthStatus {
case .notDetermined: requestCameraPermission()
case .authorized:
let imagePicker = UIImagePickerController()
imagePicker.delegate = context.coordinator
imagePicker.allowsEditing = true
imagePicker.sourceType = sourceType
return imagePicker
case .restricted, .denied: self.alertCameraAccessNeeded = true
@unknown default:
fatalError()
}
}
func requestCameraPermission() {
AVCaptureDevice.requestAccess(for: .video, completionHandler: {accessGranted in
guard accessGranted == true else { return }
})
}
func makeCoordinator() -> Coordinator {
Coordinator(self, userManager: userManager)
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {
}
class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let parent: ImagePicker
let userManager: UserManager
init(_ parent: ImagePicker, userManager: UserManager) {
self.parent = parent
self.userManager = userManager
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[.editedImage] as? UIImage {
parent.selectedImage = image
userManager.uploadProfilePicture(image: image)
}
parent.presentationMode.wrappedValue.dismiss()
}
}
}
Run Code Online (Sandbox Code Playgroud)
jn_*_*pdx 11
为了回应您的评论,想知道如何请求权限并仅有条件地显示图像选择器,这里有一个简单的示例,它允许您强制执行操作(例如,设置 @State 变量)或有条件地显示视图,如果你有许可。
在 中请求许可onAppear,但也可以移动到按下按钮或类似的操作。
class CameraManager : ObservableObject {
@Published var permissionGranted = false
func requestPermission() {
AVCaptureDevice.requestAccess(for: .video, completionHandler: {accessGranted in
DispatchQueue.main.async {
self.permissionGranted = accessGranted
}
})
}
}
struct ContentView: View {
@StateObject var cameraManager = CameraManager()
var body: some View {
VStack {
Text("Hello, world")
if cameraManager.permissionGranted {
//show a conditional view only if you have permission
}
}
.onReceive(cameraManager.$permissionGranted, perform: { (granted) in
if granted {
//show image picker controller
}
})
.onAppear {
cameraManager.requestPermission()
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6205 次 |
| 最近记录: |