系统有自带的图库和相机功能,这里介绍一下如何用代码打开它们(模拟器是不支持打开相机的)和如何选取本地图片上传到图库
事前准备:
#import@interface ViewController () { //设置为全局变量 UIImagePickerController*_pc1; UIImagePickerController*_pc2;}
一.UIImagePickerControllerSourceTypePhotoLibrary图片库
//初始化 _pc1=[[UIImagePickerController alloc]init]; //类型 PhotoLibrary--图库 _pc1.sourceType=UIImagePickerControllerSourceTypePhotoLibrary; //是否允许编辑 _pc1.allowsEditing=YES; //签署代理 _pc1.delegate=self; //显示 [self presentViewController:_pc1 animated:YES completion:^{ //显示完成后执行的代码 }];
注意:这时运行代码是不会进入图库的,还需要在info.plist文件中,加入
Privacy - Photo Library Usage Description
在弹出的窗口中,选择允许,就可以进入到图库页面了
二.UIImagePickerControllerSourceTypeCamera 相机(模拟器是无法使用的)
这里要增加一段判读语句,判断当前相机状态是否可以使用
//判断当前是否支持相机 //Authorization--授权 Status--地位 //Capture--获取 Device--工具 //Restricted--受限制 Denied--拒绝 AVAuthorizationStatus authStatus=[AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]; if (authStatus==AVAuthorizationStatusRestricted||authStatus==AVAuthorizationStatusDenied ){ NSLog(@"相机权限受限"); return; } //判断相机是否可以正常使用 //Available - 可获得的 if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]==NO) { NSLog(@"相机无法使用"); return; } _pc2=[[UIImagePickerController alloc]init]; _pc2.sourceType=UIImagePickerControllerSourceTypeCamera; _pc2.delegate=self; _pc2.allowsEditing=YES; [self presentViewController:_pc2 animated:YES completion:^{ //显示后执行的代码 }];
三.回调方法
①取消的响应方法
//点击了Cancel的响应方法-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{ //退出当前界面 [_pk dismissViewControllerAnimated:YES completion:^{ }];}
②图片回调的方法,可以用来本地上传到图片库
//选择图片回调-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary*)info{ //info是一个字典,储存的是编辑后的图片和原图 //UIImagePickerControllerEditedImage - 编辑后的图片 //UIImagePickerControllerOriginalImage - 原图 UIImage *image = info[@"UIImagePickerControllerEditedImage"]; //保存到图库 UIImageWriteToSavedPhotosAlbum(image, self, @selector(), nil); [_pk dismissViewControllerAnimated:YES completion:^{ }];}