导入头文件和库
#import <MobileCoreServices/UTCoreTypes.h>
MobileCoreServices.framework
UIImagePickerController是图像选取器,可以照相录制和照片库进行读取片源显示.
<UIImagePickerControllerDelegate, UINavigationControllerDelegate>使用的时候要符合这两个协议.接着是使用协议方法进行读取拍摄的照片或者照片库里的照片.
使用方法如下: 设置并打开照片库或者相机
NSArray* mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:sourceType];//返回可用的类型
if ( [UIImagePickerController isSourceTypeAvailable:sourceType]
&& [mediaTypes count] > 0) {
UIImagePickerController* picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.mediaTypes = mediaTypes;
picker.allowsEditing = YES;
picker.sourceType = sourceType; //设置选取器的数据原来,可以来自相机也可以来自照片库.
[self presentViewController:picker animated:YES completion:nil];
}else{
UIAlertView *alert =
[[UIAlertView alloc] initWithTitle:@"Error accessing media"
message:@"Device doesn’t support that media source."
delegate:nil
cancelButtonTitle:@"Drat!"
otherButtonTitles:nil];
[alert show];
}
选取后,在协议方法里获取数据:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{ //选区后执行的方法
NSString* mediaType = info[UIImagePickerControllerMediaType];
if ( [mediaType isEqual:(NSString*)kUTTypeImage] ) { //如果是照片图片的话执行
UIImage* imagee = info[UIImagePickerControllerEditedImage];
self.image = image;
}else if ( [mediaType isEqual:(NSString*)kUTTypeMovie] ){ //如果影片的话执行
self.mediaURl = info[UIImagePickerControllerMediaURL];
}
[picker dismissViewControllerAnimated:YES completion:nil];
}
//点取消后执行的方法
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:nil];
}