Skip to content

Instantly share code, notes, and snippets.

@trilliwon
Created August 2, 2020 08:45
Show Gist options
  • Save trilliwon/0d7cee0d430df8587aa4328ebf760997 to your computer and use it in GitHub Desktop.
Save trilliwon/0d7cee0d430df8587aa4328ebf760997 to your computer and use it in GitHub Desktop.
import AVFoundation
import Photos
import UIKit
import UserNotifications
protocol PermissionCheckable {
func doAfterNotificationPermission(workItem: ((Bool) -> Void)?)
func doAfterVideoPermission(workItem: ((Bool) -> Void)?)
func doAfterPhotoPermission(workItem: ((Bool) -> Void)?)
}
extension PermissionCheckable where Self: UIViewController {
func doAfterNotificationPermission(workItem: ((Bool) -> Void)? = nil) {
checkForNotification { hasPermission in
workItem?(hasPermission)
}
}
func doAfterVideoPermission(workItem: ((Bool) -> Void)?) {
checkForVideo { hasPermission in
workItem?(hasPermission)
}
}
func doAfterPhotoPermission(workItem: ((Bool) -> Void)?) {
checkForPhotoLibrary { hasPermission in
workItem?(hasPermission)
}
}
private func checkForNotification(completion: ((Bool) -> Void)?) {
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.getNotificationSettings { settings in
switch settings.authorizationStatus {
case .authorized:
completion?(true)
case .notDetermined:
notificationCenter.requestAuthorization(options: [.criticalAlert, .alert, .sound]) { granted, _ in
completion?(granted)
}
case .denied:
self.alert(message: "Notification permission Denied", okTitle: "Ok") {
completion?(false)
}
case .provisional:
completion?(true)
@unknown default:
print("@")
}
}
}
private func checkForVideo(completion: ((Bool) -> Void)?) {
switch AVCaptureDevice.authorizationStatus(for: AVMediaType.video) {
case .authorized:
completion?(true)
case .restricted:
alert(message: "Video Permission Restriced", okTitle: "Ok") {
completion?(false)
}
case .denied:
alert(message: "Video Permission Denied", okTitle: "Ok") {
completion?(false)
}
case .notDetermined:
AVCaptureDevice.requestAccess(for: .video) { granted in
DispatchQueue.main.async {
completion?(granted)
}
}
@unknown default:
print("@")
}
}
private func checkForPhotoLibrary(completion: ((Bool) -> Void)?) {
switch PHPhotoLibrary.authorizationStatus() {
case .authorized:
completion?(true)
case .restricted:
alert(message: "Video Permission Denied", okTitle: "Ok") {
completion?(false)
}
case .denied:
alert(message: "Video Permission Denied", okTitle: "Ok") {
completion?(false)
}
case .notDetermined:
PHPhotoLibrary.requestAuthorization { [weak self] status in
if status != .authorized {
self?.checkForPhotoLibrary(completion: completion)
} else {
DispatchQueue.main.async {
completion?(true)
}
}
}
@unknown default:
print("@")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment