iOS开发 使用系统的相册和相机
第一步,在info.plist文件中添加两个key,
相机权限
<key>NSPhotoLibraryUsageDescription</key>
<string>photoLibraryDesciption</string>
相册权限
<key>NSCameraUsageDescription</key>
<string>cameraDesciption</string>
第二步、在使用到的头文件中导入代理
UINavigationControllerDelegate, UIImagePickerControllerDelegate
第三步、使用系统提供的调用方法
UIAlertAction *a1=[UIAlertAction actionWithTitle:@"使用照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES; //可编辑
//判断是否可以打开照相机
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
//摄像头
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[ws presentViewController:picker animated:YES completion:nil];
}
else{
NSLog(@"没有摄像头");
}
}];
UIAlertAction *a2=[UIAlertAction actionWithTitle:@"使用相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
// 获取支持的媒体格式
NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
// 判断是否支持需要设置的sourceType
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
UIImagePickerController *_imagePickerController=[[UIImagePickerController alloc] init];
_imagePickerController.delegate=self;
// 1、设置图片拾取器上的sourceType
_imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
// 2、设置支持的媒体格式
//_imagePickerController.mediaTypes = @[mediaTypes[0]];
// 3、其他设置
_imagePickerController.allowsEditing = YES; // 如果设置为NO,当用户选择了图片之后不会进入图像编辑界面。
// 4、推送图片拾取器控制器
[ws presentViewController:_imagePickerController animated:YES completion:^{
NSLog(@"dakai");
}];
}
}];
UIAlertAction *a3=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:a1];
[alert addAction:a2];
[alert addAction:a3];
第四部实现代理方法
// 拍照完成回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo NS_DEPRECATED_IOS(2_0, 3_0)
{
if(picker.sourceType == UIImagePickerControllerSourceTypeCamera){
//图片存入相册
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
[[WWSideslipViewController defaultWWSideVC] dismissViewControllerAnimated:YES completion:nil];
}
//进入拍摄页面点击取消按钮
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[[WWSideslipViewController defaultWWSideVC] dismissViewControllerAnimated:YES completion:nil];
}