iOS--调用相机和相册

在平常的项目开发中,有时我们会需要调用系统相机和相册,苹果提供了很方便的API接口,我们只需要拿过来使用就可以了,另外特别注意由于在模拟器上不能进行摄像头拍摄,没有相机设备,必须在真机上进行调试,所以在编写代码的时候,必须进行判断当前设备是否有相机设备,话不多说,直接上代码

1.调用相机

//调用相机

- (IBAction)photoClick:(UIButton *)sender {

    //判断当前设备是否有相机,模拟器中无法使用相机功能

    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {


        UIImagePickerController *picker=[[UIImagePickerController alloc]init];

        picker.delegate=self;

        picker.sourceType=UIImagePickerControllerSourceTypeCamera;//来自摄像头

        picker.allowsEditing=NO;//是否可编辑

    }

    else{

        //没有相机设备

        UIAlertController *alertC=[UIAlertController alertControllerWithTitle:@"提醒" message:@"当前设备没有相机设备" preferredStyle:UIAlertControllerStyleAlert];

        

        UIAlertAction *sureAction=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        }];

        [alertC addAction:sureAction];

        [self presentViewController:alertC animated:YES completion:nil];

    }

}


2,调用相册

//调用相册

- (IBAction)pictureClick:(UIButton *)sender {

    //在模拟器上可以调取相册

    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {

        

        UIImagePickerController *picker=[[UIImagePickerController alloc]init];

        picker.delegate=self;

        picker.allowsEditing=YES;//是否可编辑

        picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;//来自相册

        [self presentViewController:picker animated:YES completion:nil];

   }

}

3,
另外需要实现 UIImagePickerControllerDelegate协议方法

#pragma mark-UIImagePickerControllerDelegate

//拍摄完成后或者点击相册中的照片点击使用执行的方法

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info

{

    //获取到图片

    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];

    //将图片存储到相册

    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

    [self dismissViewControllerAnimated:YES completion:nil];//返回原界面

}


//点击cancle(取消)之后执行的代码

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{

    [self dismissViewControllerAnimated:YES completion:nil];

}

你可能感兴趣的:(iOS)