iOS 8에서 카메라 권한 대화 상자 표시
내 앱이 iOS 8에서 처음으로 카메라에 액세스하려고하면 iOS 7의 마이크 액세스를위한 마이크와 매우 유사한 카메라 권한 대화 상자가 사용자에게 표시됩니다.
iOS 7에서는 미리 마이크 권한 대화 상자를 호출하고 권한이 부여되었는지 확인할 수있었습니다 ( 예 : 이 질문 참조 ). iOS 8에서 카메라 권한 대화 상자를 호출하는 유사한 방법이 있습니까? 마이크와 카메라 액세스 권한을 위해 대화 상자를 결합 할 수 있습니까?
다음은 우리가 사용한 접근 방식입니다.
if ([AVCaptureDevice respondsToSelector:@selector(requestAccessForMediaType: completionHandler:)]) {
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
// Will get here on both iOS 7 & 8 even though camera permissions weren't required
// until iOS 8. So for iOS 7 permission will always be granted.
if (granted) {
// Permission has been granted. Use dispatch_async for any UI updating
// code because this block may be executed in a thread.
dispatch_async(dispatch_get_main_queue(), ^{
[self doStuff];
});
} else {
// Permission has been denied.
}
}];
} else {
// We are on iOS <= 6. Just do what we need to do.
[self doStuff];
}
비슷한 문제가 발생했습니다. 사용자가 처음 메시지를 받았을 때 카메라 액세스를 거부 한 경우 버튼을 눌러 스냅 샷을 찍으면 카메라 모드에서 검은 색 화면이 나타납니다.
그러나 사용자가 액세스를 거부했음을 감지하고이를 켜야한다는 메시지를 표시하고 싶지만 현재 사용자 카메라 액세스를 확인하는 기능을 찾을 수 없습니다. 그러한 기능이 있습니까?
편집 : 다음 확인은 카메라 액세스에 대해 IOS 8에서 알려줍니다.
#import <AVFoundation/AVFoundation.h>
AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if(status == AVAuthorizationStatusAuthorized) { // authorized
}
else if(status == AVAuthorizationStatusDenied){ // denied
}
else if(status == AVAuthorizationStatusRestricted){ // restricted
}
else if(status == AVAuthorizationStatusNotDetermined){ // not determined
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
if(granted){ // Access has been granted ..do something
} else { // Access denied ..do something
}
}];
}
이 정보는 다음 질문에서 발견되었습니다 ( iOS8에서 애플리케이션에 카메라 액세스 권한이 있는지 여부를 프로그래밍 방식으로 확인하는 방법 ).
여기에 제 스위프트 솔루션 (iOS 8)이 있습니다. QR 스캔을 위해 카메라가 필요했기 때문에 사용을 요청해야했습니다.
이것은 제공합니다
사용자가 기본 허용 카메라 액세스 질문 전에 허용을 선택하도록 권장합니다.
사용자가 첫 번째 요청을 거부 한 경우 설정에 액세스하는 쉬운 방법입니다.
ViewDidAppear / 또는 ViewDidLoad 등에서 호출 확인 카메라를 실행하려면 viewDidAppear를 사용해야하므로 내 사용자 지정 카메라보기 제약 조건이 설정되었습니다.
func checkCamera() {
let authStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
switch authStatus {
case .authorized: break // Do your stuff here i.e. allowScanning()
case .denied: alertToEncourageCameraAccessInitially()
case .notDetermined: alertPromptToAllowCameraAccessViaSetting()
default: alertToEncourageCameraAccessInitially()
}
}
func alertToEncourageCameraAccessInitially() {
let alert = UIAlertController(
title: "IMPORTANT",
message: "Camera access required for QR Scanning",
preferredStyle: UIAlertControllerStyle.alert
)
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Allow Camera", style: .cancel, handler: { (alert) -> Void in
UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
}))
present(alert, animated: true, completion: nil)
}
func alertPromptToAllowCameraAccessViaSetting() {
let alert = UIAlertController(
title: "IMPORTANT",
message: "Please allow camera access for QR Scanning",
preferredStyle: UIAlertControllerStyle.alert
)
alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel) { alert in
if AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo).count > 0 {
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { granted in
DispatchQueue.main.async() {
self.checkCamera() } }
}
}
)
present(alert, animated: true, completion: nil)
}
dispatch_async 사용에 대한 팁에 대한 위의 jamix 덕분에 새로 설정된 카메라 기능을 훨씬 빠르게 표시하도록 응답합니다.
후행 폐쇄의 혼합에 대해 죄송합니다 .. 시도하고 싶었습니다.
대답 중 어느 것도 마이크와 카메라 권한을 모두 확인하지 않는 것 같습니다. 우리 코드는 카메라 권한이 부여되었지만 마이크 액세스가 거부 된 시나리오를 확인합니다.
우리는 Swift를 처음 접했기 때문에 중첩 된 클로저와 if문장이 최적 일 것 같지 않습니다 . 코드 개선을위한 제안을 공유 해주세요! 그러나 적어도 지금까지는 테스트에서 작동합니다.
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (videoGranted: Bool) -> Void in
if (videoGranted) {
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeAudio, completionHandler: { (audioGranted: Bool) -> Void in
if (audioGranted) {
dispatch_async(dispatch_get_main_queue()) {
// Both video & audio granted
}
} else {
// Rejected audio
}
})
} else {
// Rejected video
}
})
Swift 3.0 솔루션
수입 AVFoundation
참고 : Info.plist에 개인 정보 보호-카메라 사용 설명 키 추가
// MARK : 카메라 취급
func callCamera(){
let myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.camera
self.present(myPickerController, animated: true, completion: nil)
NSLog("Camera");
}
func checkCamera() {
let authStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
switch authStatus {
case .authorized: callCamera() // Do your stuff here i.e. callCameraMethod()
case .denied: alertToEncourageCameraAccessInitially()
case .notDetermined: alertPromptToAllowCameraAccessViaSetting()
default: alertToEncourageCameraAccessInitially()
}
}
func alertToEncourageCameraAccessInitially() {
let alert = UIAlertController(
title: "IMPORTANT",
message: "Camera access required for capturing photos!",
preferredStyle: UIAlertControllerStyle.alert
)
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Allow Camera", style: .cancel, handler: { (alert) -> Void in
UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
}))
present(alert, animated: true, completion: nil)
}
func alertPromptToAllowCameraAccessViaSetting() {
let alert = UIAlertController(
title: "IMPORTANT",
message: "Camera access required for capturing photos!",
preferredStyle: UIAlertControllerStyle.alert
)
alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel) { alert in
if AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo).count > 0 {
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { granted in
DispatchQueue.main.async() {
self.checkCamera() } }
}
}
)
present(alert, animated: true, completion: nil)
}
나를 위해 iOS7 및 iOS8에서이 작업 :
ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];
switch (status) {
case ALAuthorizationStatusAuthorized:
break;
case ALAuthorizationStatusRestricted:
case ALAuthorizationStatusDenied:
break;
case ALAuthorizationStatusNotDetermined:
break;
}
Swift 3의 경우 viewWillAppear첫 번째 뷰 컨트롤러 의 메서드 에 다음을 추가 할 수 있습니다 .
먼저 AVFoundation프레임 워크 가져 오기
import AVFoundation
그때:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let authorizationStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
switch authorizationStatus {
case .notDetermined:
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { granted in
if granted {
print("access granted")
}
else {
print("access denied")
}
}
case .authorized:
print("Access authorized")
case .denied, .restricted:
print("restricted")
}
}
Privacy - Camera Usage Description키 를 추가하는 것을 잊지 마십시오.Info.plist
앱 대리자에 대한 액세스를 확인합니다.
import UIKit
import AVFoundation
import Photos
func applicationDidBecomeActive(application: UIApplication) {
cameraAllowsAccessToApplicationCheck()
internetAvailabilityOnApplicationCheck()
photoLibraryAvailabilityCheck()
}
//MARK:- CAMERA ACCESS CHECK
func cameraAllowsAccessToApplicationCheck()
{
let authorizationStatus = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo)
switch authorizationStatus {
case .NotDetermined:
// permission dialog not yet presented, request authorization
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo,
completionHandler: { (granted:Bool) -> Void in
if granted {
print("access granted")
}
else {
print("access denied")
}
})
case .Authorized:
print("Access authorized")
case .Denied, .Restricted:
alertToEncourageCameraAccessWhenApplicationStarts()
default:
print("DO NOTHING")
}
}
//MARK:- PHOTO LIBRARY ACCESS CHECK
func photoLibraryAvailabilityCheck()
{
if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.Authorized
{
}
else
{
var cameraUnavailableAlertController = UIAlertController (title: "Photo Library Unavailable", message: "Please check to see if device settings doesn't allow photo library access", preferredStyle: .Alert)
var settingsAction = UIAlertAction(title: "Settings", style: .Destructive) { (_) -> Void in
let settingsUrl = NSURL(string:UIApplicationOpenSettingsURLString)
if let url = settingsUrl {
UIApplication.sharedApplication().openURL(url)
}
}
var cancelAction = UIAlertAction(title: "Okay", style: .Default, handler: nil)
cameraUnavailableAlertController .addAction(settingsAction)
cameraUnavailableAlertController .addAction(cancelAction)
self.window?.rootViewController!.presentViewController(cameraUnavailableAlertController , animated: true, completion: nil)
}
}
func internetAvailabilityOnApplicationCheck()
{
//MARK:- INTERNET AVAILABLITY
if InternetReachability.isConnectedToNetwork() {
}
else
{
dispatch_async(dispatch_get_main_queue(), {
//INTERNET NOT AVAILABLE ALERT
var internetUnavailableAlertController = UIAlertController (title: "Network Unavailable", message: "Please check your internet connection settings and turn on Network Connection", preferredStyle: .Alert)
var settingsAction = UIAlertAction(title: "Settings", style: .Destructive) { (_) -> Void in
let settingsUrl = NSURL(string:UIApplicationOpenSettingsURLString)
if let url = settingsUrl {
UIApplication.sharedApplication().openURL(url)
}
}
var cancelAction = UIAlertAction(title: "Okay", style: .Default, handler: nil)
internetUnavailableAlertController .addAction(settingsAction)
internetUnavailableAlertController .addAction(cancelAction)
self.window?.rootViewController!.presentViewController(internetUnavailableAlertController , animated: true, completion: nil)
})
}
}
*
나를 위해 문제는 것이 었습니다 Bundle name및 Bundle Display Name때문에 최근의 빌드 구성 변경 내 Info.plist 파일에 설정되지 않습니다되었다. 가능성이없는 사건 같은데 ...하지만이 문제를 해결하는 데 몇 시간이 걸렸습니다. 다른 사람에게 도움이되기를 바랍니다.
참고 URL : https://stackoverflow.com/questions/25803217/presenting-camera-permission-dialog-in-ios-8
'IT TIP' 카테고리의 다른 글
| Visual Studio Code에서 강조 텍스트 색 변경 (0) | 2020.10.30 |
|---|---|
| jquery / ajax를 사용하여 Div의 콘텐츠 새로 고침 / 다시로드 (0) | 2020.10.30 |
| 번개 모양 디자인 만들기 (예 : The Flash) (0) | 2020.10.30 |
| Android facebook applicationId는 null 일 수 없습니다. (0) | 2020.10.30 |
| Swift를 사용하여 iOS에서 오른쪽에서 왼쪽으로 뷰 컨트롤러를 표시하는 방법 (0) | 2020.10.30 |