Last active
November 14, 2019 12:35
-
-
Save SaurabhPrajapati/7b38383ee971aa9332a7f221d3bb2d41 to your computer and use it in GitHub Desktop.
PermissionManager for swift permissions
This file contains 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
// | |
// PermissionManager.swift | |
// IDRNDVoiceDemo | |
// | |
// Created by Saurabh on 14/11/19. | |
// | |
import Foundation | |
import AVFoundation | |
import Speech | |
enum Permission { | |
case camera | |
case speech | |
case audio | |
} | |
class PermissionManager { | |
static let shared = PermissionManager() | |
private var permissions: [Permission: Bool] | |
private init() { | |
permissions = [:] | |
} | |
private func askCameraPermission() { | |
AVCaptureDevice.requestAccess(for: AVMediaType.video) {[weak self] response in | |
self?.permissions[.camera] = response | |
} | |
} | |
private func askSpeechPermission() { | |
SFSpeechRecognizer.requestAuthorization {[weak self] authStatus in | |
self?.permissions[.speech] = authStatus == .authorized | |
} | |
} | |
private func askAudioPermissions() { | |
AVAudioSession.sharedInstance().requestRecordPermission {[weak self] allowed in | |
self?.permissions[.audio] = allowed | |
} | |
} | |
func askPermissions(_ permissions: [Permission]) { | |
for permission in permissions { | |
askPermission(permission) | |
} | |
} | |
func askPermission(_ permission: Permission) { | |
switch permission { | |
case .camera: | |
askCameraPermission() | |
case .speech: | |
askSpeechPermission() | |
case .audio: | |
askAudioPermissions() | |
} | |
} | |
subscript(permission: Permission) -> Bool { | |
return permissions[permission] ?? false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment