본문 바로가기

개발 코딩 정보 공유/애플 iOS 스위프트 Xcode

IOS 권한체크와 로직처리

 

 

안녕하세요. 김과자 입니다.

IOS나 안드로이드에서 위치정보나, 파일쓰기... 등

해당 기능을 사용하기 위해서는 사용자 권한체크는 필수 입니다.

오늘은 IOS의 권한체크 부분을 알아보겠습니다.

 

위와 같이 프로젝트의 Plist.info 내부에 작업이 필요합니다.

해당 메세지는 런타임시 권한 체크 할때 출력되는 메세지 입니다.

유저에게 권한을 요청하고 허용인지 아닌지를 판단하여 분기 처리 하면 됩니다.

단 특이 사항은 단 한번만 묻기 때문에 유저가 거부로 설정할시에 설정 화면에서 바꾸도록 유도하도록 UI/UX를 구성해야 합니다.

IOS 앱에서 기능 사용중 설정으로 넘어가는 경우 많이들 보셨을 겁니다.

우선 소스 살펴 보겠습니다.

 

 
 //카메라 권한을 묻는 예시
 let dialog = UIAlertController(title: "주의", message: "설정에서 권한을 허용해야 합니다.", preferredStyle: .alert)
 let action = UIAlertAction(title: "확인", style: UIAlertActionStyle.default)
 dialog.addAction(action)        

//카메라 권한 묻기
AVCaptureDevice.requestAccess(for: .video) { auth in
if auth {
	//권한 획득시 실행될 명령
	//...
} else {
	self.present(dialog, animated: true, completion: nil)
}
}

 

아래는 보시다 시피 필요한 부분에서 권한 체크를 통해 분기처리를 하면됩니다.

//상태값을 확인하여 분기처리 하면 됩니다.
let status = AVCaptureDevice.authorizationStatus(for: type)
if (status != .authorized){
	//권한이 없다면 -> 셋팅으로 넘김
	let alert = UIAlertController(title: "권한요청", message: "권한이 필요합니다. 권한 설정 화면으로 이동합니다.", preferredStyle: .alert)
    let okAction = UIAlertAction(title: "확인", style: .default, handler: { _ in
      if (UIApplication.shared.canOpenURL(URL(string: UIApplication.openSettingsURLString)!)){
          UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
      }
    })
    alert.addAction(okAction)
    present(alert, animated: true, completion: nil)
}

 

아래와 같이 권한체크후 요청을 하는 로직으로 처리하셔도 됩니다.

//사진앨범 권한을 위한 예시
if PHPhotoLibrary.authorizationStatus() == .notDetermined {
	PHPhotoLibrary.requestAuthorization { (_) in
		//...
	}
} else {
	callback()
}

 

 


 

 

<참조문서>

https://developer.apple.com/design/human-interface-guidelines/ios/app-architecture/accessing-user-data/