1。导入库,实现协议
#import <MobileCoreServices/MobileCoreServices.h>
<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
e.g.
- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
__block BOOL result = NO;
if ([paramMediaType length] == 0){
NSLog(@"Media type is empty.");
return NO;
}
//获取本机中符合指定资源的所有媒体类型,以便后续判定是否支持
NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
[availableMediaTypes enumerateObjectsUsingBlock:
^(id obj, NSUInteger idx, BOOL *stop) {
NSString *mediaType = (NSString *)obj;
if ([mediaType isEqualToString:paramMediaType]){
result = YES;
*stop= YES;
}
}];
return result;
}
//是否支持摄像
- (BOOL) doesCameraSupportTakingVideos{
//KUTTypeMovie : 视频
return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypeCamera];
}
//是否可用摄像头
- (BOOL) isCameraAvailable{
return [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera];
}
//delegate:完成选择,注意这里的视频数据并未被保存(到机子中)
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSLog(@"Picker returned successfully.");
NSLog(@"infoOfPickedMedia:%@", info); //info:包含了挑选的媒体信息
NSString *mediaType = info[UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(__bridge NSString *)kUTTypeMovie]){ //挑选的是视频
NSURL *urlOfVideo = info[UIImagePickerControllerMediaURL];
NSLog(@"Video URL = %@", urlOfVideo);
NSError *dataReadingError = nil;
//获取到的录制数据
NSData *videoData = [NSDatadataWithContentsOfURL:urlOfVideo
options:NSDataReadingMapped error:&dataReadingError];
if (videoData != nil){
NSLog(@"Successfully loaded the data.");
} else {
NSLog(@"Failed to load the data with error = %@", dataReadingError);
}
}
[picker dismissViewControllerAnimated:YES completion:nil];
}
//delegate 取消选择
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
NSLog(@"Picker was cancelled");
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)actionDisplayPickerController {
if ([self isCameraAvailable] && [self doesCameraSupportTakingVideos]){
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
controller.sourceType = UIImagePickerControllerSourceTypeCamera;
//mediaType:KUTTypeImage / KUTTypeMovie 这里决定了出现的模式窗口imagePickerController是进行摄像还是进行照相
controller.mediaTypes = @[(__bridge NSString *)kUTTypeMovie];
controller.allowsEditing= YES;
controller.delegate = self;
/* 录制质量 UIImagePickerControllerQualityTypeHigh / UIImagePickerControllerQualityTypeMedium */
controller.videoQuality = UIImagePickerControllerQualityTypeHigh;
/* 允许摄录的时间 (秒) */
controller.videoMaximumDuration = 30.0f;
[self presentViewController:controller animated:YES completion:nil];
} else {
NSLog(@"Camera is not available.");
}
}