题外话:很久就该写了,到今天才备份,不应该。
当App要上传图片时会给出 alert 提示,选择『相册』,『拍照』。
当第一次安装 APP时,由于没有授权APP访问权限
导入类库
#import <AssetsLibrary/AssetsLibrary.h>
ViewController 实现两个代理:UINavigationControllerDelegate,UIImagePickerControllerDelegate
相册
ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied)
{
//无权限,拒绝访问
[self showAlertViewWithTips:[KHString_Alert stringForPhotoNoAuthorizationAlert] withBlockFlag:YES];//提示:请在 iPhone 的\"设置\"-\"隐私\"-\"照片\"选项中,允许**访问您的相册
return;
} else if (author == ALAuthorizationStatusNotDetermined){
//还未授权
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
if (!granted) {
//不允许访问,直接返回,不执行之后的代码,反之跳转页面。
[self showAlertViewWithTips:[KHString_Alert stringForPhotoNoAuthorizationAlert] withBlockFlag:YES];
return;
}
}];
}
....继续选择图片
相机
//先判断设备上是否有摄像头
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
[self showAlertViewWithTips:[KHString_Alert stringForDeviceNoCamera] withBlockFlag:NO];//您的设备没有摄像头
return;
}
//相机用户是否允许访问
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
{
//无权限或拒绝访问相机
[self showAlertViewWithTips:[KHString_Alert stringForCameraNoAuthorizationAlert] withBlockFlag:YES];//请在 iPhone 的\"设置\"-\"隐私\"-\"相机\"选项中,允许**访问您的相机
return;
} else if (authStatus == AVAuthorizationStatusNotDetermined){
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
if (!granted) {
[self showAlertViewWithTips:[KHString_Alert stringForCameraNoAuthorizationAlert] withBlockFlag:YES];
return;
}
}];
}
//相机拍照
调用相册或者相机
//type = UIImagePickerControllerSourceTypePhotoLibrary或UIImagePickerControllerSourceTypeCamera
if ([UIImagePickerController isSourceTypeAvailable:type])
{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.allowsEditing = YES;
imagePicker.sourceType = type;
[self presentViewController:imagePicker animated:YES completion:nil];
}
代理方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
// 获得图片
UIImage *image = info[UIImagePickerControllerEditedImage];
[picker dismissViewControllerAnimated:YES completion:nil];
}
注意
iOS8之后出现了Photos framework。可以使用Photos框架的方法。
iOS4用 AssetsLibrary