在打开相机拍照或者打开相册选择图片以前, 有必要先判断先是否有权限, 若是没有权限应该给个提示, 让用户本身去设置权限.ide
判断是否有相机权限:测试
//首先须要导入头文件: #import <AVFoundation/AVFoundation.h> // 判断是够有全向访问相机 AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]; if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) { //无权限 NSLog(@"没有访问相机权限"); return; }
判断是否有相册权限:code
网上找了不少, 都是说用另外一个类来判断的, 叫什么名字忘了, 可是是不能用的, 正确姿式是使用PHPhotoLibrary
这个类.图片
//首先须要导入头文件: #import <Photos/PHPhotoLibrary.h> // 判断是否有访问相册的权限 PHAuthorizationStatus author = [PHPhotoLibrary authorizationStatus]; if (author == PHAuthorizationStatusRestricted || author ==PHAuthorizationStatusDenied){ //无权限 NSLog(@"没有访问相册的权限"); return; }
从相机或者相册选择照片须要用到UIImagePickerController
类.ip
从相机选择照片:get
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; imagePicker.delegate = self; imagePicker.allowsEditing = YES; imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; [self presentViewController:imagePicker animated:YES completion:nil];
从相册选择照片:it
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; imagePicker.delegate = self; imagePicker.allowsEditing = YES; imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; [self presentViewController:imagePicker animated:YES completion:nil];
拍照方式选择照片时候, 通常须要将照片保存到本地相册中, 保存相册的代码只有一个方法, 以下所示.io
// 将拍照的图片保存到本地 UIImageWriteToSavedPhotosAlbum(originalImage, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
须要注意的是, 第一个参数是要保存的图片, 第二个参数是要执行方法的target, 第三个参数是selector, 第四个参数是传参数. 第三个参数selector, selector的方法名字通常是有参数的(测试写无参数的, 保存时候回崩溃).import
//此方法通常是三个参数, 不然容易出错. - (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo { NSString *message = @"呵呵"; if (!error) { message = @"成功保存到相册"; }else { message = [error description]; } NSLog(@"message is %@",message); }