在实际项目中,我们经常需要访问设备的摄像头或者相册,当第一次安装某个App的时候,系统便会弹出授权对话框,要求用户做出是否授权的判断。整体逻辑比较简单,但是在使用过程中需要对用户体验进行优化,否则会出现bug。该博客的示例代码已经上传至 https://github.com/chenyufeng1991/AuthorityOfCameraAndPhoto 。
首先我先描述一下出现的问题。我以访问相册为例,实现代码如下:
- (void)photoBtnPressed:(id)sender
{
// 首先查看当前设备是否支持相册
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
{
[self presentToImagePickerController:UIImagePickerControllerSourceTypePhotoLibrary];
}
else
{
[self showAlertController:@"提示" message:@"当前设备不支持相册"];
}
}
- (void)presentToImagePickerController:(UIImagePickerControllerSourceType)type
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = type;
[self presentViewController:picker animated:YES completion:nil];
}
- (void)showAlertController:(NSString *)title message:(NSString *)message
{
UIAlertController *ac = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
[ac addAction:[UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}]];
[self presentViewController:ac animated:YES completion:nil];
}
解释一下,首先需要判断当前设备是否支持相册,进行这样判断操作会比较安全。如果可以的话直接使用UIImagePickerContro