About the simple implementation of calling system camera and photo album functions in iOS

The easiest way to take pictures and record videos in iOS is to call UIImagePickerController. UIImagePickerController inherits from UINavigationController. When you need to use proxy methods, you need to comply with both protocols. In the past, UIImagePickerController may be used to select album pictures or take pictures. In fact, it can also be used to shoot video.

Using UIImagePickerController to take pictures or video mainly follow the following steps:

  • Create a global UIImagePickerController object.

  • Specify the source sourceType of UIImagePickerController, whether it comes from UIImagePickerControllerSourceTypeCamera camera, or from UIImagePickerControllerSourceTypePhotoLibrary album.

  • Then it is to set the mediaTypes media type, which is an option that must be set for recording video. By default, it is kUTTypeImage (note: the setting of mediaTypes is under the MobileCoreServices framework), and some other video-related properties can also be set. For example: videoQuality of video Quality, videoMaximumDuration The maximum recording duration of the video (default is 10s), the direction of the cameraDevice camera (default is the rear camera).

  • Specify the camera's capture mode cameraCaptureMode, set the capture mode after setting mediaTypes, note that the capture mode needs to be set when the camera source sourceType is camera, otherwise a crash will occur.

  • Display UIImagePickerController at the appropriate time, and then save and get the picture or video in the corresponding proxy method.

Let's go to the code below, it's more clear...
First of all, you need to import the following header files, and comply with the two proxy methods

#import "ViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
@interface ViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
    UIImagePickerController *_imagePickerController;
}

Create UIImagePickerController object

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib

    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;

从摄像头获取图片或视频

#pragma mark 从摄像头获取图片或视频
- (void)selectImageFromCamera
{
    _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    //录制视频时长,默认10s
    _imagePickerController.videoMaximumDuration = 15;

    //相机类型(拍照、录像...)字符串需要做相应的类型转换
    _imagePickerController.mediaTypes = @[(NSString *)kUTTypeMovie,(NSString *)kUTTypeImage];

    //视频上传质量
    //UIImagePickerControllerQualityTypeHigh高清
    //UIImagePickerControllerQualityTypeMedium中等质量
    //UIImagePickerControllerQualityTypeLow低质量
    //UIImagePickerControllerQualityType640x480
    _imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;

    //设置摄像头模式(拍照,录制视频)为录像模式
    _imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
    [self presentViewController:_imagePickerController animated:YES completion:nil];
}

从相册获取图片或视频

#pragma mark 从相册获取图片或视频
- (void)selectImageFromAlbum
{
    //NSLog(@"相册");
    _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    [self presentViewController:_imagePickerController animated:YES completion:nil];
}

在imagePickerController:didFinishPickingMediaWithInfo:代理方法中处理得到的资源,保存本地并上传...

#pragma mark UIImagePickerControllerDelegate
//该代理方法仅适用于只选取图片时
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo {
    NSLog(@"选择完毕----image:%@-----info:%@",image,editingInfo);
}
//适用获取所有媒体资源,只需判断资源类型
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    //判断资源类型
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]){
        //如果是图片
        self.imageView.image = info[UIImagePickerControllerEditedImage];
        //压缩图片
        NSData *fileData = UIImageJPEGRepresentation(self.imageView.image, 1.0);
        //保存图片至相册
        UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
        //上传图片
        [self uploadImageWithData:fileData];

    }else{
        //如果是视频
        NSURL *url = info[UIImagePickerControllerMediaURL];
        //播放视频
        _moviePlayer.contentURL = url;
        [_moviePlayer play];
        //保存视频至相册(异步线程)
        NSString *urlStr = [url path];

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {

                UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
            }
        });
        NSData *videoData = [NSData dataWithContentsOfURL:url];
        //视频上传
        [self uploadVideoWithData:videoData];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

图片和视频保存完毕后的回调

#pragma mark 图片保存完毕的回调
- (void) image: (UIImage *) image didFinishSavingWithError:(NSError *) error contextInfo: (void *)contextInf{

}

#pragma mark 视频保存完毕的回调
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInf{
    if (error) {
        NSLog(@"保存视频过程中发生错误,错误信息:%@",error.localizedDescription);
    }else{
        NSLog(@"视频保存成功.");
    }
}

以上仅是简单功能的实现,还有例如切换前后摄像头、闪光灯设置、对焦、曝光模式等更多功能...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324803375&siteId=291194637