如果您的App里需要获得由系统自带的照相机、摄像机和录音软件所生成的文件。可以借鉴以下代码来调用iPhone摄像头拍照或者摄像的功能,并把获得的数据直接写入到文件。
//这一段是,点击一个takePicture按钮的操作.
01 | - (IBAction)takePicture:(id)sender { |
03 | UIImagePickerController *picker = [[UIImagePickerController alloc] init]; |
05 | if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { |
06 | picker.sourceType = UIImagePickerControllerSourceTypeCamera; |
07 | NSArray *temp_MediaTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType]; |
08 | picker.mediaTypes = temp_MediaTypes; |
09 | picker.delegate = self; |
10 | picker.allowsImageEditing = YES; |
13 | [self presentModalViewController:picker animated:YES]; |
//下面两个函数是遵守 UIImagePickerControllerDelegate这个协议所实现的类.这样就能够完整的实现,获取照片或者视频,然后写入文件的过程.
01 | - ( void )imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info |
04 | NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType]; |
07 | NSFileManager *fileManager = [NSFileManager defaultManager]; |
10 | NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); |
11 | NSString *documentsDirectory = [paths objectAtIndex:0]; |
13 | if ([mediaType isEqualToString:@ "public.image" ]){ |
15 | UIImage *image = [info objectForKey:@ "UIImagePickerControllerEditedImage" ]; |
16 | ; NSLog(@“found an image”); |
18 | NSString *imageFile = [documentsDirectory stringByAppendingPathComponent:@ "temp.jpg" ]; |
19 | ; NSLog(@“%@”, ,imageFile); |
21 | success = [fileManager fileExistsAtPath:imageFile]; |
23 | success = [fileManager removeItemAtPath:imageFile error:>error]; |
26 | imageView.image = image; |
27 | [UIImageJPEGRepresentation(image, 1.0f) writeToFile:imageFile atomically:YES]; |
32 | else if ([mediaType isEqualToString:@ "public.movie" ]){ |
33 | NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL]; |
34 | NSLog(@“%@”, ,videoURL); |
35 | NSLog(@“found a video”); |
36 | NSData *videoData = [NSData dataWithContentsOfURL:videoURL]; |
40 | NSString *videoFile = [documentsDirectory stringByAppendingPathComponent:@ "temp.mov" ]; |
41 | ; NSLog(@“%@”, ,videoFile); |
43 | success = [fileManager fileExistsAtPath:videoFile]; |
45 | success = [fileManager removeItemAtPath:videoFile error:>error]; |
47 | [videoData writeToFile:videoFile atomically:YES]; |
51 | [picker dismissModalViewControllerAnimated:YES]; |
54 | - ( void )imagePickerControllerDidCancel:(UIImagePickerController *)picker { |
56 | [picker dismissModalViewControllerAnimated:YES]; |