You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

149 lines
4.2 KiB

//
// SystemAuthority.swift
// FunDoHealth
//
// Created by ecell on 2018/5/5.
// Copyright © 2020 ecell. All rights reserved.
//
import Foundation
import CoreLocation
import Photos
fileprivate enum AuthorityType {
case location
case photos
case camera
}
final class SystemAuthority: NSObject {
///
static let shared = SystemAuthority()
private override init() {}
//
typealias resultBlock = (Bool) -> ()
var resultAAA: resultBlock?
// MARK:-
private let locationManager = CLLocationManager()
func getLocationAuthority(result: @escaping resultBlock) {
//
switch CLLocationManager.authorizationStatus() {
case .notDetermined:
//
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
//
locationManager.delegate = self
resultAAA = result
case .restricted, .denied:
//
alertSetAuthority(type: .location)
result(false)
case .authorizedAlways, .authorizedWhenInUse:
//
result(true)
default: break
}
}
// MARK:-
func getPhotoAuthority(result: @escaping resultBlock) {
let status = PHPhotoLibrary.authorizationStatus()
//
if status == .authorized {
result(true)
return
}
//
if status == .notDetermined {
PHPhotoLibrary.requestAuthorization { [weak self] newstatus in
if newstatus == .authorized {
result(true)
return
}
//
self?.alertSetAuthority(type: .photos)
result(false)
}
return
}
//
alertSetAuthority(type: .photos)
result(false)
}
// MARK:-
func getCameraAuthority(result: @escaping resultBlock) {
let status = AVCaptureDevice.authorizationStatus(for: .video)
if status == .authorized {
result(true)
return
}
if status == .notDetermined {
AVCaptureDevice.requestAccess(for: .video) { [weak self] granted in
result(granted)
if !granted {
//
self?.alertSetAuthority(type: .camera)
}
}
return
}
//
alertSetAuthority(type: .camera)
result(false)
}
}
// MARK:-
extension SystemAuthority: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .restricted, .denied:
//
resultAAA!(false)
break
case .authorizedAlways, .authorizedWhenInUse:
resultAAA!(true)
break
case .notDetermined: break
default: break
}
}
}
// MARK:-
extension SystemAuthority {
fileprivate func alertSetAuthority(type: AuthorityType) {
var title: String = ""
switch type {
case .location: break
case .photos:
title = MultiLanguageKey.photoTip.localized
case .camera:
title = MultiLanguageKey.cameraiTip.localized
}
if let vc = keyWindow.rootViewController {
showAlert(vc, title, cancelText: MultiLanguageKey.cancel.localized, confirmText: MultiLanguageKey.open.localized) { (result) in
if result {
if let url = URL(string: UIApplication.openSettingsURLString) {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
}
}
}
}
}
}
}