【发布时间】:2021-10-13 16:44:52
【问题描述】:
我正在处理一个 swift 项目,并且有一个问题要重构我的代码。
我正在编写代码来检查用户是否在应用程序中同时授权了摄像头和麦克风授权。我编写了以下代码,但我想(并且我希望)我可以重构代码,因为我认为下面的代码不清楚。我了解了基本的 Swift 语法,并逐渐了解了编译语言,但请告诉我是否有办法使其更具可读性或更易于编写。
我想在这里做的是......
-
检查摄像头和麦克风是否都被授权。
-
如果两者都被授权,则使用 showNextVC() 显示视图控制器。
-
如果其中一项或两项均未获得授权,则使用 showConfigurationAlert 显示警报
func checkAuthStatus(){ checkCameraStatus() } func checkCameraStatus() { switch AVCaptureDevice.authorizationStatus(for: .video) { case .notDetermined: print("not Determined") AVCaptureDevice.requestAccess(for: .video) { granted in if granted { print("Now it's granted") } } case .restricted: print("restricted") showConfigurationAlert(for: "camera") case .denied: print("denied") showConfigurationAlert(for: "camera") case .authorized: checkMicrophoneStatus() @unknown default: print("unknown") } } func checkMicrophoneStatus() { switch AVCaptureDevice.authorizationStatus(for: .audio){ case .notDetermined: AVCaptureDevice.requestAccess(for: .audio) { granted in if granted { print("Now it's granted") } } case .restricted: print("restricted") showConfigurationAlert(for: "microphone") case .denied: print("denied") showConfigurationAlert(for: "microphone") case .authorized: print(("authorized")) showNextVC() @unknown default: print("unknown") } }
我所做的是,首先在 checkAuthStatus 中检查相机授权,然后,如果相机被授权,则触发 checkMicrophoneStatus() 以检查麦克风授权。 我认为这段代码不清楚的原因是,我只在 checkAuthStatus() 函数中编写了一个检查相机授权的函数。我想如果我能写出类似的东西很清楚
func checkAuthStatus(){
// check both cameara and microphone is authorized.
// if both of them are authorized, show next VC with showNextVC() function.
}
【问题讨论】:
-
如果摄像头授权状态未确定,则请求许可,然后
checkCameraStatus会立即返回,对麦克风不做任何操作,无论用户选择什么选项。这是故意的吗?
标签: ios swift switch-statement refactoring