Advertisement
Guest User

Front-facing camera by default in PhoneGap

a guest
Jan 8th, 2014
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 42.87 KB | None | 0 0
  1. /*
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9.  
  10. http://www.apache.org/licenses/LICENSE-2.0
  11.  
  12. Unless required by applicable law or agreed to in writing,
  13. software distributed under the License is distributed on an
  14. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. KIND, either express or implied. See the License for the
  16. specific language governing permissions and limitations
  17. under the License.
  18. */
  19.  
  20. #import "CDVCapture.h"
  21. #import <Cordova/CDVJSON.h>
  22. #import <Cordova/CDVAvailability.h>
  23.  
  24. #define kW3CMediaFormatHeight @"height"
  25. #define kW3CMediaFormatWidth @"width"
  26. #define kW3CMediaFormatCodecs @"codecs"
  27. #define kW3CMediaFormatBitrate @"bitrate"
  28. #define kW3CMediaFormatDuration @"duration"
  29. #define kW3CMediaModeType @"type"
  30.  
  31. @implementation CDVImagePicker
  32.  
  33. @synthesize quality;
  34. @synthesize callbackId;
  35. @synthesize mimeType;
  36.  
  37. - (uint64_t)accessibilityTraits
  38. {
  39. NSString* systemVersion = [[UIDevice currentDevice] systemVersion];
  40.  
  41. if (([systemVersion compare:@"4.0" options:NSNumericSearch] != NSOrderedAscending)) { // this means system version is not less than 4.0
  42. return UIAccessibilityTraitStartsMediaSession;
  43. }
  44.  
  45. return UIAccessibilityTraitNone;
  46. }
  47.  
  48. - (BOOL)prefersStatusBarHidden {
  49. return YES;
  50. }
  51.  
  52. - (UIViewController*)childViewControllerForStatusBarHidden {
  53. return nil;
  54. }
  55.  
  56. - (void)viewWillAppear:(BOOL)animated {
  57. SEL sel = NSSelectorFromString(@"setNeedsStatusBarAppearanceUpdate");
  58. if ([self respondsToSelector:sel]) {
  59. [self performSelector:sel withObject:nil afterDelay:0];
  60. }
  61.  
  62. [super viewWillAppear:animated];
  63. }
  64.  
  65. @end
  66.  
  67. @implementation CDVCapture
  68. @synthesize inUse;
  69.  
  70. - (id)initWithWebView:(UIWebView*)theWebView
  71. {
  72. self = (CDVCapture*)[super initWithWebView:theWebView];
  73. if (self) {
  74. self.inUse = NO;
  75. }
  76. return self;
  77. }
  78.  
  79. - (void)captureAudio:(CDVInvokedUrlCommand*)command
  80. {
  81. NSString* callbackId = command.callbackId;
  82. NSDictionary* options = [command.arguments objectAtIndex:0];
  83.  
  84. if ([options isKindOfClass:[NSNull class]]) {
  85. options = [NSDictionary dictionary];
  86. }
  87.  
  88. NSNumber* duration = [options objectForKey:@"duration"];
  89. // the default value of duration is 0 so use nil (no duration) if default value
  90. if (duration) {
  91. duration = [duration doubleValue] == 0 ? nil : duration;
  92. }
  93. CDVPluginResult* result = nil;
  94.  
  95. if (NSClassFromString(@"AVAudioRecorder") == nil) {
  96. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageToErrorObject:CAPTURE_NOT_SUPPORTED];
  97. } else if (self.inUse == YES) {
  98. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageToErrorObject:CAPTURE_APPLICATION_BUSY];
  99. } else {
  100. // all the work occurs here
  101. CDVAudioRecorderViewController* audioViewController = [[CDVAudioRecorderViewController alloc] initWithCommand:self duration:duration callbackId:callbackId];
  102.  
  103. // Now create a nav controller and display the view...
  104. CDVAudioNavigationController* navController = [[CDVAudioNavigationController alloc] initWithRootViewController:audioViewController];
  105.  
  106. self.inUse = YES;
  107.  
  108. SEL selector = NSSelectorFromString(@"presentViewController:animated:completion:");
  109. if ([self.viewController respondsToSelector:selector]) {
  110. [self.viewController presentViewController:navController animated:YES completion:nil];
  111. } else {
  112. // deprecated as of iOS >= 6.0
  113. [self.viewController presentModalViewController:navController animated:YES];
  114. }
  115. }
  116.  
  117. if (result) {
  118. [self.commandDelegate sendPluginResult:result callbackId:callbackId];
  119. }
  120. }
  121.  
  122. - (void)captureImage:(CDVInvokedUrlCommand*)command
  123. {
  124. NSString* callbackId = command.callbackId;
  125. NSDictionary* options = [command.arguments objectAtIndex:0];
  126.  
  127. if ([options isKindOfClass:[NSNull class]]) {
  128. options = [NSDictionary dictionary];
  129. }
  130.  
  131. // options could contain limit and mode neither of which are supported at this time
  132. // taking more than one picture (limit) is only supported if provide own controls via cameraOverlayView property
  133. // can support mode in OS
  134.  
  135. if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
  136. NSLog(@"Capture.imageCapture: camera not available.");
  137. CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageToErrorObject:CAPTURE_NOT_SUPPORTED];
  138. [self.commandDelegate sendPluginResult:result callbackId:callbackId];
  139. } else {
  140. if (pickerController == nil) {
  141. pickerController = [[CDVImagePicker alloc] init];
  142. }
  143.  
  144. pickerController.delegate = self;
  145. pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
  146. pickerController.allowsEditing = NO;
  147. pickerController.cameraDevice = UIImagePickerControllerCameraDeviceFront;
  148. if ([pickerController respondsToSelector:@selector(mediaTypes)]) {
  149. // iOS 3.0
  150. pickerController.mediaTypes = [NSArray arrayWithObjects:(NSString*)kUTTypeImage, nil];
  151. }
  152.  
  153. /*if ([pickerController respondsToSelector:@selector(cameraCaptureMode)]){
  154. // iOS 4.0
  155. pickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
  156. pickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
  157. pickerController.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
  158. }*/
  159. // CDVImagePicker specific property
  160. pickerController.callbackId = callbackId;
  161.  
  162. SEL selector = NSSelectorFromString(@"presentViewController:animated:completion:");
  163. if ([self.viewController respondsToSelector:selector]) {
  164. [self.viewController presentViewController:pickerController animated:YES completion:nil];
  165. } else {
  166. // deprecated as of iOS >= 6.0
  167. [self.viewController presentModalViewController:pickerController animated:YES];
  168. }
  169. }
  170. }
  171.  
  172. /* Process a still image from the camera.
  173. * IN:
  174. * UIImage* image - the UIImage data returned from the camera
  175. * NSString* callbackId
  176. */
  177. - (CDVPluginResult*)processImage:(UIImage*)image type:(NSString*)mimeType forCallbackId:(NSString*)callbackId
  178. {
  179. CDVPluginResult* result = nil;
  180.  
  181. // save the image to photo album
  182. UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
  183.  
  184. NSData* data = nil;
  185. if (mimeType && [mimeType isEqualToString:@"image/png"]) {
  186. data = UIImagePNGRepresentation(image);
  187. } else {
  188. data = UIImageJPEGRepresentation(image, 0.5);
  189. }
  190.  
  191. // write to temp directory and return URI
  192. NSString* docsPath = [NSTemporaryDirectory()stringByStandardizingPath]; // use file system temporary directory
  193. NSError* err = nil;
  194. NSFileManager* fileMgr = [[NSFileManager alloc] init];
  195.  
  196. // generate unique file name
  197. NSString* filePath;
  198. int i = 1;
  199. do {
  200. filePath = [NSString stringWithFormat:@"%@/photo_%03d.jpg", docsPath, i++];
  201. } while ([fileMgr fileExistsAtPath:filePath]);
  202.  
  203. if (![data writeToFile:filePath options:NSAtomicWrite error:&err]) {
  204. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageToErrorObject:CAPTURE_INTERNAL_ERR];
  205. if (err) {
  206. NSLog(@"Error saving image: %@", [err localizedDescription]);
  207. }
  208. } else {
  209. // create MediaFile object
  210.  
  211. NSDictionary* fileDict = [self getMediaDictionaryFromPath:filePath ofType:mimeType];
  212. NSArray* fileArray = [NSArray arrayWithObject:fileDict];
  213.  
  214. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:fileArray];
  215. }
  216.  
  217. return result;
  218. }
  219.  
  220. - (void)captureVideo:(CDVInvokedUrlCommand*)command
  221. {
  222. NSString* callbackId = command.callbackId;
  223. NSDictionary* options = [command.arguments objectAtIndex:0];
  224.  
  225. if ([options isKindOfClass:[NSNull class]]) {
  226. options = [NSDictionary dictionary];
  227. }
  228.  
  229. // options could contain limit, duration and mode
  230. // taking more than one video (limit) is only supported if provide own controls via cameraOverlayView property
  231. NSNumber* duration = [options objectForKey:@"duration"];
  232. NSString* mediaType = nil;
  233.  
  234. if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
  235. // there is a camera, it is available, make sure it can do movies
  236. pickerController = [[CDVImagePicker alloc] init];
  237.  
  238. NSArray* types = nil;
  239. if ([UIImagePickerController respondsToSelector:@selector(availableMediaTypesForSourceType:)]) {
  240. types = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
  241. // NSLog(@"MediaTypes: %@", [types description]);
  242.  
  243. if ([types containsObject:(NSString*)kUTTypeMovie]) {
  244. mediaType = (NSString*)kUTTypeMovie;
  245. } else if ([types containsObject:(NSString*)kUTTypeVideo]) {
  246. mediaType = (NSString*)kUTTypeVideo;
  247. }
  248. }
  249. }
  250. if (!mediaType) {
  251. // don't have video camera return error
  252. NSLog(@"Capture.captureVideo: video mode not available.");
  253. CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageToErrorObject:CAPTURE_NOT_SUPPORTED];
  254. [self.commandDelegate sendPluginResult:result callbackId:callbackId];
  255. pickerController = nil;
  256. } else {
  257. pickerController.delegate = self;
  258. pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
  259. pickerController.allowsEditing = NO;
  260. pickerController.cameraDevice = UIImagePickerControllerCameraDeviceFront;
  261. // iOS 3.0
  262. pickerController.mediaTypes = [NSArray arrayWithObjects:mediaType, nil];
  263.  
  264. if ([mediaType isEqualToString:(NSString*)kUTTypeMovie]){
  265. if (duration) {
  266. pickerController.videoMaximumDuration = [duration doubleValue];
  267. }
  268. //NSLog(@"pickerController.videoMaximumDuration = %f", pickerController.videoMaximumDuration);
  269. }
  270.  
  271. // iOS 4.0
  272. if ([pickerController respondsToSelector:@selector(cameraCaptureMode)]) {
  273. pickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
  274. // pickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
  275. // pickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
  276. // pickerController.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
  277. }
  278. // CDVImagePicker specific property
  279. pickerController.callbackId = callbackId;
  280.  
  281. SEL selector = NSSelectorFromString(@"presentViewController:animated:completion:");
  282. if ([self.viewController respondsToSelector:selector]) {
  283. [self.viewController presentViewController:pickerController animated:YES completion:nil];
  284. } else {
  285. // deprecated as of iOS >= 6.0
  286. [self.viewController presentModalViewController:pickerController animated:YES];
  287. }
  288. }
  289. }
  290.  
  291. - (CDVPluginResult*)processVideo:(NSString*)moviePath forCallbackId:(NSString*)callbackId
  292. {
  293. // save the movie to photo album (only avail as of iOS 3.1)
  294.  
  295. /* don't need, it should automatically get saved
  296. NSLog(@"can save %@: %d ?", moviePath, UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(moviePath));
  297. if (&UIVideoAtPathIsCompatibleWithSavedPhotosAlbum != NULL && UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(moviePath) == YES) {
  298. NSLog(@"try to save movie");
  299. UISaveVideoAtPathToSavedPhotosAlbum(moviePath, nil, nil, nil);
  300. NSLog(@"finished saving movie");
  301. }*/
  302. // create MediaFile object
  303. NSDictionary* fileDict = [self getMediaDictionaryFromPath:moviePath ofType:nil];
  304. NSArray* fileArray = [NSArray arrayWithObject:fileDict];
  305.  
  306. return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:fileArray];
  307. }
  308.  
  309. - (void)getMediaModes:(CDVInvokedUrlCommand*)command
  310. {
  311. // NSString* callbackId = [arguments objectAtIndex:0];
  312. // NSMutableDictionary* imageModes = nil;
  313. NSArray* imageArray = nil;
  314. NSArray* movieArray = nil;
  315. NSArray* audioArray = nil;
  316.  
  317. if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
  318. // there is a camera, find the modes
  319. // can get image/jpeg or image/png from camera
  320.  
  321. /* can't find a way to get the default height and width and other info
  322. * for images/movies taken with UIImagePickerController
  323. */
  324. NSDictionary* jpg = [NSDictionary dictionaryWithObjectsAndKeys:
  325. [NSNumber numberWithInt:0], kW3CMediaFormatHeight,
  326. [NSNumber numberWithInt:0], kW3CMediaFormatWidth,
  327. @"image/jpeg", kW3CMediaModeType,
  328. nil];
  329. NSDictionary* png = [NSDictionary dictionaryWithObjectsAndKeys:
  330. [NSNumber numberWithInt:0], kW3CMediaFormatHeight,
  331. [NSNumber numberWithInt:0], kW3CMediaFormatWidth,
  332. @"image/png", kW3CMediaModeType,
  333. nil];
  334. imageArray = [NSArray arrayWithObjects:jpg, png, nil];
  335.  
  336. if ([UIImagePickerController respondsToSelector:@selector(availableMediaTypesForSourceType:)]) {
  337. NSArray* types = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
  338.  
  339. if ([types containsObject:(NSString*)kUTTypeMovie]) {
  340. NSDictionary* mov = [NSDictionary dictionaryWithObjectsAndKeys:
  341. [NSNumber numberWithInt:0], kW3CMediaFormatHeight,
  342. [NSNumber numberWithInt:0], kW3CMediaFormatWidth,
  343. @"video/quicktime", kW3CMediaModeType,
  344. nil];
  345. movieArray = [NSArray arrayWithObject:mov];
  346. }
  347. }
  348. }
  349. NSDictionary* modes = [NSDictionary dictionaryWithObjectsAndKeys:
  350. imageArray ? (NSObject*) imageArray:[NSNull null], @"image",
  351. movieArray ? (NSObject*) movieArray:[NSNull null], @"video",
  352. audioArray ? (NSObject*) audioArray:[NSNull null], @"audio",
  353. nil];
  354. NSString* jsString = [NSString stringWithFormat:@"navigator.device.capture.setSupportedModes(%@);", [modes JSONString]];
  355. [self.commandDelegate evalJs:jsString];
  356. }
  357.  
  358. - (void)getFormatData:(CDVInvokedUrlCommand*)command
  359. {
  360. NSString* callbackId = command.callbackId;
  361. // existence of fullPath checked on JS side
  362. NSString* fullPath = [command.arguments objectAtIndex:0];
  363. // mimeType could be null
  364. NSString* mimeType = nil;
  365.  
  366. if ([command.arguments count] > 1) {
  367. mimeType = [command.arguments objectAtIndex:1];
  368. }
  369. BOOL bError = NO;
  370. CDVCaptureError errorCode = CAPTURE_INTERNAL_ERR;
  371. CDVPluginResult* result = nil;
  372.  
  373. if (!mimeType || [mimeType isKindOfClass:[NSNull class]]) {
  374. // try to determine mime type if not provided
  375. id command = [self.commandDelegate getCommandInstance:@"File"];
  376. bError = !([command isKindOfClass:[CDVFile class]]);
  377. if (!bError) {
  378. CDVFile* cdvFile = (CDVFile*)command;
  379. mimeType = [cdvFile getMimeTypeFromPath:fullPath];
  380. if (!mimeType) {
  381. // can't do much without mimeType, return error
  382. bError = YES;
  383. errorCode = CAPTURE_INVALID_ARGUMENT;
  384. }
  385. }
  386. }
  387. if (!bError) {
  388. // create and initialize return dictionary
  389. NSMutableDictionary* formatData = [NSMutableDictionary dictionaryWithCapacity:5];
  390. [formatData setObject:[NSNull null] forKey:kW3CMediaFormatCodecs];
  391. [formatData setObject:[NSNumber numberWithInt:0] forKey:kW3CMediaFormatBitrate];
  392. [formatData setObject:[NSNumber numberWithInt:0] forKey:kW3CMediaFormatHeight];
  393. [formatData setObject:[NSNumber numberWithInt:0] forKey:kW3CMediaFormatWidth];
  394. [formatData setObject:[NSNumber numberWithInt:0] forKey:kW3CMediaFormatDuration];
  395.  
  396. if ([mimeType rangeOfString:@"image/"].location != NSNotFound) {
  397. UIImage* image = [UIImage imageWithContentsOfFile:fullPath];
  398. if (image) {
  399. CGSize imgSize = [image size];
  400. [formatData setObject:[NSNumber numberWithInteger:imgSize.width] forKey:kW3CMediaFormatWidth];
  401. [formatData setObject:[NSNumber numberWithInteger:imgSize.height] forKey:kW3CMediaFormatHeight];
  402. }
  403. } else if (([mimeType rangeOfString:@"video/"].location != NSNotFound) && (NSClassFromString(@"AVURLAsset") != nil)) {
  404. NSURL* movieURL = [NSURL fileURLWithPath:fullPath];
  405. AVURLAsset* movieAsset = [[AVURLAsset alloc] initWithURL:movieURL options:nil];
  406. CMTime duration = [movieAsset duration];
  407. [formatData setObject:[NSNumber numberWithFloat:CMTimeGetSeconds(duration)] forKey:kW3CMediaFormatDuration];
  408.  
  409. NSArray* allVideoTracks = [movieAsset tracksWithMediaType:AVMediaTypeVideo];
  410. if ([allVideoTracks count] > 0) {
  411. AVAssetTrack* track = [[movieAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
  412. CGSize size = [track naturalSize];
  413.  
  414. [formatData setObject:[NSNumber numberWithFloat:size.height] forKey:kW3CMediaFormatHeight];
  415. [formatData setObject:[NSNumber numberWithFloat:size.width] forKey:kW3CMediaFormatWidth];
  416. // not sure how to get codecs or bitrate???
  417. // AVMetadataItem
  418. // AudioFile
  419. } else {
  420. NSLog(@"No video tracks found for %@", fullPath);
  421. }
  422. } else if ([mimeType rangeOfString:@"audio/"].location != NSNotFound) {
  423. if (NSClassFromString(@"AVAudioPlayer") != nil) {
  424. NSURL* fileURL = [NSURL fileURLWithPath:fullPath];
  425. NSError* err = nil;
  426.  
  427. AVAudioPlayer* avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&err];
  428. if (!err) {
  429. // get the data
  430. [formatData setObject:[NSNumber numberWithDouble:[avPlayer duration]] forKey:kW3CMediaFormatDuration];
  431. if ([avPlayer respondsToSelector:@selector(settings)]) {
  432. NSDictionary* info = [avPlayer settings];
  433. NSNumber* bitRate = [info objectForKey:AVEncoderBitRateKey];
  434. if (bitRate) {
  435. [formatData setObject:bitRate forKey:kW3CMediaFormatBitrate];
  436. }
  437. }
  438. } // else leave data init'ed to 0
  439. }
  440. }
  441. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:formatData];
  442. // NSLog(@"getFormatData: %@", [formatData description]);
  443. }
  444. if (bError) {
  445. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageToErrorObject:errorCode];
  446. }
  447. if (result) {
  448. [self.commandDelegate sendPluginResult:result callbackId:callbackId];
  449. }
  450. }
  451.  
  452. - (NSDictionary*)getMediaDictionaryFromPath:(NSString*)fullPath ofType:(NSString*)type
  453. {
  454. NSFileManager* fileMgr = [[NSFileManager alloc] init];
  455. NSMutableDictionary* fileDict = [NSMutableDictionary dictionaryWithCapacity:5];
  456.  
  457. [fileDict setObject:[fullPath lastPathComponent] forKey:@"name"];
  458. [fileDict setObject:fullPath forKey:@"fullPath"];
  459. // determine type
  460. if (!type) {
  461. id command = [self.commandDelegate getCommandInstance:@"File"];
  462. if ([command isKindOfClass:[CDVFile class]]) {
  463. CDVFile* cdvFile = (CDVFile*)command;
  464. NSString* mimeType = [cdvFile getMimeTypeFromPath:fullPath];
  465. [fileDict setObject:(mimeType != nil ? (NSObject*)mimeType : [NSNull null]) forKey:@"type"];
  466. }
  467. }
  468. NSDictionary* fileAttrs = [fileMgr attributesOfItemAtPath:fullPath error:nil];
  469. [fileDict setObject:[NSNumber numberWithUnsignedLongLong:[fileAttrs fileSize]] forKey:@"size"];
  470. NSDate* modDate = [fileAttrs fileModificationDate];
  471. NSNumber* msDate = [NSNumber numberWithDouble:[modDate timeIntervalSince1970] * 1000];
  472. [fileDict setObject:msDate forKey:@"lastModifiedDate"];
  473.  
  474. return fileDict;
  475. }
  476.  
  477. - (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingImage:(UIImage*)image editingInfo:(NSDictionary*)editingInfo
  478. {
  479. // older api calls new one
  480. [self imagePickerController:picker didFinishPickingMediaWithInfo:editingInfo];
  481. }
  482.  
  483. /* Called when image/movie is finished recording.
  484. * Calls success or error code as appropriate
  485. * if successful, result contains an array (with just one entry since can only get one image unless build own camera UI) of MediaFile object representing the image
  486. * name
  487. * fullPath
  488. * type
  489. * lastModifiedDate
  490. * size
  491. */
  492. - (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
  493. {
  494. CDVImagePicker* cameraPicker = (CDVImagePicker*)picker;
  495. NSString* callbackId = cameraPicker.callbackId;
  496.  
  497. if ([picker respondsToSelector:@selector(presentingViewController)]) {
  498. [[picker presentingViewController] dismissModalViewControllerAnimated:YES];
  499. } else {
  500. [[picker parentViewController] dismissModalViewControllerAnimated:YES];
  501. }
  502.  
  503. CDVPluginResult* result = nil;
  504.  
  505. UIImage* image = nil;
  506. NSString* mediaType = [info objectForKey:UIImagePickerControllerMediaType];
  507. if (!mediaType || [mediaType isEqualToString:(NSString*)kUTTypeImage]) {
  508. // mediaType is nil then only option is UIImagePickerControllerOriginalImage
  509. if ([UIImagePickerController respondsToSelector:@selector(allowsEditing)] &&
  510. (cameraPicker.allowsEditing && [info objectForKey:UIImagePickerControllerEditedImage])) {
  511. image = [info objectForKey:UIImagePickerControllerEditedImage];
  512. } else {
  513. image = [info objectForKey:UIImagePickerControllerOriginalImage];
  514. }
  515. }
  516. if (image != nil) {
  517. // mediaType was image
  518. result = [self processImage:image type:cameraPicker.mimeType forCallbackId:callbackId];
  519. } else if ([mediaType isEqualToString:(NSString*)kUTTypeMovie]) {
  520. // process video
  521. NSString* moviePath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
  522. if (moviePath) {
  523. result = [self processVideo:moviePath forCallbackId:callbackId];
  524. }
  525. }
  526. if (!result) {
  527. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageToErrorObject:CAPTURE_INTERNAL_ERR];
  528. }
  529. [self.commandDelegate sendPluginResult:result callbackId:callbackId];
  530. pickerController = nil;
  531. }
  532.  
  533. - (void)imagePickerControllerDidCancel:(UIImagePickerController*)picker
  534. {
  535. CDVImagePicker* cameraPicker = (CDVImagePicker*)picker;
  536. NSString* callbackId = cameraPicker.callbackId;
  537.  
  538. if ([picker respondsToSelector:@selector(presentingViewController)]) {
  539. [[picker presentingViewController] dismissModalViewControllerAnimated:YES];
  540. } else {
  541. [[picker parentViewController] dismissModalViewControllerAnimated:YES];
  542. }
  543.  
  544. CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageToErrorObject:CAPTURE_NO_MEDIA_FILES];
  545. [self.commandDelegate sendPluginResult:result callbackId:callbackId];
  546. pickerController = nil;
  547. }
  548.  
  549. @end
  550.  
  551. @implementation CDVAudioNavigationController
  552.  
  553. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 60000
  554. - (NSUInteger)supportedInterfaceOrientations
  555. {
  556. // delegate to CVDAudioRecorderViewController
  557. return [self.topViewController supportedInterfaceOrientations];
  558. }
  559. #endif
  560.  
  561. @end
  562.  
  563. @interface CDVAudioRecorderViewController () {
  564. UIStatusBarStyle _previousStatusBarStyle;
  565. }
  566. @end
  567.  
  568. @implementation CDVAudioRecorderViewController
  569. @synthesize errorCode, callbackId, duration, captureCommand, doneButton, recordingView, recordButton, recordImage, stopRecordImage, timerLabel, avRecorder, avSession, pluginResult, timer, isTimed;
  570.  
  571. - (NSString*)resolveImageResource:(NSString*)resource
  572. {
  573. NSString* systemVersion = [[UIDevice currentDevice] systemVersion];
  574. BOOL isLessThaniOS4 = ([systemVersion compare:@"4.0" options:NSNumericSearch] == NSOrderedAscending);
  575.  
  576. // the iPad image (nor retina) differentiation code was not in 3.x, and we have to explicitly set the path
  577. // if user wants iPhone only app to run on iPad they must remove *~ipad.* images from CDVCapture.bundle
  578. if (isLessThaniOS4) {
  579. NSString* iPadResource = [NSString stringWithFormat:@"%@~ipad.png", resource];
  580. if (CDV_IsIPad() && [UIImage imageNamed:iPadResource]) {
  581. return iPadResource;
  582. } else {
  583. return [NSString stringWithFormat:@"%@.png", resource];
  584. }
  585. }
  586.  
  587. return resource;
  588. }
  589.  
  590. - (id)initWithCommand:(CDVCapture*)theCommand duration:(NSNumber*)theDuration callbackId:(NSString*)theCallbackId
  591. {
  592. if ((self = [super init])) {
  593. self.captureCommand = theCommand;
  594. self.duration = theDuration;
  595. self.callbackId = theCallbackId;
  596. self.errorCode = CAPTURE_NO_MEDIA_FILES;
  597. self.isTimed = self.duration != nil;
  598. _previousStatusBarStyle = [UIApplication sharedApplication].statusBarStyle;
  599.  
  600. return self;
  601. }
  602.  
  603. return nil;
  604. }
  605.  
  606. - (void)loadView
  607. {
  608. if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) {
  609. self.edgesForExtendedLayout = UIRectEdgeNone;
  610. }
  611.  
  612. // create view and display
  613. CGRect viewRect = [[UIScreen mainScreen] applicationFrame];
  614. UIView* tmp = [[UIView alloc] initWithFrame:viewRect];
  615.  
  616. // make backgrounds
  617. NSString* microphoneResource = @"CDVCapture.bundle/microphone";
  618.  
  619. if (CDV_IsIPhone5()) {
  620. microphoneResource = @"CDVCapture.bundle/microphone-568h";
  621. }
  622.  
  623. UIImage* microphone = [UIImage imageNamed:[self resolveImageResource:microphoneResource]];
  624. UIView* microphoneView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, viewRect.size.width, microphone.size.height)];
  625. [microphoneView setBackgroundColor:[UIColor colorWithPatternImage:microphone]];
  626. [microphoneView setUserInteractionEnabled:NO];
  627. [microphoneView setIsAccessibilityElement:NO];
  628. [tmp addSubview:microphoneView];
  629.  
  630. // add bottom bar view
  631. UIImage* grayBkg = [UIImage imageNamed:[self resolveImageResource:@"CDVCapture.bundle/controls_bg"]];
  632. UIView* controls = [[UIView alloc] initWithFrame:CGRectMake(0, microphone.size.height, viewRect.size.width, grayBkg.size.height)];
  633. [controls setBackgroundColor:[UIColor colorWithPatternImage:grayBkg]];
  634. [controls setUserInteractionEnabled:NO];
  635. [controls setIsAccessibilityElement:NO];
  636. [tmp addSubview:controls];
  637.  
  638. // make red recording background view
  639. UIImage* recordingBkg = [UIImage imageNamed:[self resolveImageResource:@"CDVCapture.bundle/recording_bg"]];
  640. UIColor* background = [UIColor colorWithPatternImage:recordingBkg];
  641. self.recordingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, viewRect.size.width, recordingBkg.size.height)];
  642. [self.recordingView setBackgroundColor:background];
  643. [self.recordingView setHidden:YES];
  644. [self.recordingView setUserInteractionEnabled:NO];
  645. [self.recordingView setIsAccessibilityElement:NO];
  646. [tmp addSubview:self.recordingView];
  647.  
  648. // add label
  649. self.timerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, viewRect.size.width, recordingBkg.size.height)];
  650. // timerLabel.autoresizingMask = reSizeMask;
  651. [self.timerLabel setBackgroundColor:[UIColor clearColor]];
  652. [self.timerLabel setTextColor:[UIColor whiteColor]];
  653. #ifdef __IPHONE_6_0
  654. [self.timerLabel setTextAlignment:NSTextAlignmentCenter];
  655. #else
  656. // for iOS SDK < 6.0
  657. [self.timerLabel setTextAlignment:UITextAlignmentCenter];
  658. #endif
  659. [self.timerLabel setText:@"0:00"];
  660. [self.timerLabel setAccessibilityHint:NSLocalizedString(@"recorded time in minutes and seconds", nil)];
  661. self.timerLabel.accessibilityTraits |= UIAccessibilityTraitUpdatesFrequently;
  662. self.timerLabel.accessibilityTraits &= ~UIAccessibilityTraitStaticText;
  663. [tmp addSubview:self.timerLabel];
  664.  
  665. // Add record button
  666.  
  667. self.recordImage = [UIImage imageNamed:[self resolveImageResource:@"CDVCapture.bundle/record_button"]];
  668. self.stopRecordImage = [UIImage imageNamed:[self resolveImageResource:@"CDVCapture.bundle/stop_button"]];
  669. self.recordButton.accessibilityTraits |= [self accessibilityTraits];
  670. self.recordButton = [[UIButton alloc] initWithFrame:CGRectMake((viewRect.size.width - recordImage.size.width) / 2, (microphone.size.height + (grayBkg.size.height - recordImage.size.height) / 2), recordImage.size.width, recordImage.size.height)];
  671. [self.recordButton setAccessibilityLabel:NSLocalizedString(@"toggle audio recording", nil)];
  672. [self.recordButton setImage:recordImage forState:UIControlStateNormal];
  673. [self.recordButton addTarget:self action:@selector(processButton:) forControlEvents:UIControlEventTouchUpInside];
  674. [tmp addSubview:recordButton];
  675.  
  676. // make and add done button to navigation bar
  677. self.doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissAudioView:)];
  678. [self.doneButton setStyle:UIBarButtonItemStyleDone];
  679. self.navigationItem.rightBarButtonItem = self.doneButton;
  680.  
  681. [self setView:tmp];
  682. }
  683.  
  684. - (void)viewDidLoad
  685. {
  686. [super viewDidLoad];
  687. UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil);
  688. NSError* error = nil;
  689.  
  690. if (self.avSession == nil) {
  691. // create audio session
  692. self.avSession = [AVAudioSession sharedInstance];
  693. if (error) {
  694. // return error if can't create recording audio session
  695. NSLog(@"error creating audio session: %@", [[error userInfo] description]);
  696. self.errorCode = CAPTURE_INTERNAL_ERR;
  697. [self dismissAudioView:nil];
  698. }
  699. }
  700.  
  701. // create file to record to in temporary dir
  702.  
  703. NSString* docsPath = [NSTemporaryDirectory()stringByStandardizingPath]; // use file system temporary directory
  704. NSError* err = nil;
  705. NSFileManager* fileMgr = [[NSFileManager alloc] init];
  706.  
  707. // generate unique file name
  708. NSString* filePath;
  709. int i = 1;
  710. do {
  711. filePath = [NSString stringWithFormat:@"%@/audio_%03d.wav", docsPath, i++];
  712. } while ([fileMgr fileExistsAtPath:filePath]);
  713.  
  714. NSURL* fileURL = [NSURL fileURLWithPath:filePath isDirectory:NO];
  715.  
  716. // create AVAudioPlayer
  717. self.avRecorder = [[AVAudioRecorder alloc] initWithURL:fileURL settings:nil error:&err];
  718. if (err) {
  719. NSLog(@"Failed to initialize AVAudioRecorder: %@\n", [err localizedDescription]);
  720. self.avRecorder = nil;
  721. // return error
  722. self.errorCode = CAPTURE_INTERNAL_ERR;
  723. [self dismissAudioView:nil];
  724. } else {
  725. self.avRecorder.delegate = self;
  726. [self.avRecorder prepareToRecord];
  727. self.recordButton.enabled = YES;
  728. self.doneButton.enabled = YES;
  729. }
  730. }
  731.  
  732. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 60000
  733. - (NSUInteger)supportedInterfaceOrientations
  734. {
  735. NSUInteger orientation = UIInterfaceOrientationMaskPortrait; // must support portrait
  736. NSUInteger supported = [captureCommand.viewController supportedInterfaceOrientations];
  737.  
  738. orientation = orientation | (supported & UIInterfaceOrientationMaskPortraitUpsideDown);
  739. return orientation;
  740. }
  741. #endif
  742.  
  743. - (void)viewDidUnload
  744. {
  745. [self setView:nil];
  746. [self.captureCommand setInUse:NO];
  747. }
  748.  
  749. - (void)processButton:(id)sender
  750. {
  751. if (self.avRecorder.recording) {
  752. // stop recording
  753. [self.avRecorder stop];
  754. self.isTimed = NO; // recording was stopped via button so reset isTimed
  755. // view cleanup will occur in audioRecordingDidFinishRecording
  756. } else {
  757. // begin recording
  758. [self.recordButton setImage:stopRecordImage forState:UIControlStateNormal];
  759. self.recordButton.accessibilityTraits &= ~[self accessibilityTraits];
  760. [self.recordingView setHidden:NO];
  761. __block NSError* error = nil;
  762.  
  763. void (^startRecording)(void) = ^{
  764. [self.avSession setCategory:AVAudioSessionCategoryRecord error:&error];
  765. [self.avSession setActive:YES error:&error];
  766. if (error) {
  767. // can't continue without active audio session
  768. self.errorCode = CAPTURE_INTERNAL_ERR;
  769. [self dismissAudioView:nil];
  770. } else {
  771. if (self.duration) {
  772. self.isTimed = true;
  773. [self.avRecorder recordForDuration:[duration doubleValue]];
  774. } else {
  775. [self.avRecorder record];
  776. }
  777. [self.timerLabel setText:@"0.00"];
  778. self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5f target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
  779. self.doneButton.enabled = NO;
  780. }
  781. UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil);
  782. };
  783.  
  784. SEL rrpSel = NSSelectorFromString(@"requestRecordPermission:");
  785. if ([self.avSession respondsToSelector:rrpSel])
  786. {
  787. #pragma clang diagnostic push
  788. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  789. [self.avSession performSelector:rrpSel withObject:^(BOOL granted){
  790. if (granted) {
  791. startRecording();
  792. } else {
  793. NSLog(@"Error creating audio session, microphone permission denied.");
  794. self.errorCode = CAPTURE_INTERNAL_ERR;
  795. [self dismissAudioView:nil];
  796. }
  797. }];
  798. #pragma clang diagnostic pop
  799. } else {
  800. startRecording();
  801. }
  802. }
  803. }
  804.  
  805. /*
  806. * helper method to clean up when stop recording
  807. */
  808. - (void)stopRecordingCleanup
  809. {
  810. if (self.avRecorder.recording) {
  811. [self.avRecorder stop];
  812. }
  813. [self.recordButton setImage:recordImage forState:UIControlStateNormal];
  814. self.recordButton.accessibilityTraits |= [self accessibilityTraits];
  815. [self.recordingView setHidden:YES];
  816. self.doneButton.enabled = YES;
  817. if (self.avSession) {
  818. // deactivate session so sounds can come through
  819. [self.avSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
  820. [self.avSession setActive:NO error:nil];
  821. }
  822. if (self.duration && self.isTimed) {
  823. // VoiceOver announcement so user knows timed recording has finished
  824. BOOL isUIAccessibilityAnnouncementNotification = (&UIAccessibilityAnnouncementNotification != NULL);
  825. if (isUIAccessibilityAnnouncementNotification) {
  826. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 500ull * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{
  827. UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString(@"timed recording complete", nil));
  828. });
  829. }
  830. } else {
  831. // issue a layout notification change so that VO will reannounce the button label when recording completes
  832. UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil);
  833. }
  834. }
  835.  
  836. - (void)dismissAudioView:(id)sender
  837. {
  838. // called when done button pressed or when error condition to do cleanup and remove view
  839. if ([self.captureCommand.viewController.modalViewController respondsToSelector:@selector(presentingViewController)]) {
  840. [[self.captureCommand.viewController.modalViewController presentingViewController] dismissModalViewControllerAnimated:YES];
  841. } else {
  842. [[self.captureCommand.viewController.modalViewController parentViewController] dismissModalViewControllerAnimated:YES];
  843. }
  844.  
  845. if (!self.pluginResult) {
  846. // return error
  847. self.pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageToErrorObject:self.errorCode];
  848. }
  849.  
  850. self.avRecorder = nil;
  851. [self.avSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
  852. [self.avSession setActive:NO error:nil];
  853. [self.captureCommand setInUse:NO];
  854. UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil);
  855. // return result
  856. [self.captureCommand.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
  857.  
  858. if (IsAtLeastiOSVersion(@"7.0")) {
  859. [[UIApplication sharedApplication] setStatusBarStyle:_previousStatusBarStyle];
  860. }
  861. }
  862.  
  863. - (void)updateTime
  864. {
  865. // update the label with the elapsed time
  866. [self.timerLabel setText:[self formatTime:self.avRecorder.currentTime]];
  867. }
  868.  
  869. - (NSString*)formatTime:(int)interval
  870. {
  871. // is this format universal?
  872. int secs = interval % 60;
  873. int min = interval / 60;
  874.  
  875. if (interval < 60) {
  876. return [NSString stringWithFormat:@"0:%02d", interval];
  877. } else {
  878. return [NSString stringWithFormat:@"%d:%02d", min, secs];
  879. }
  880. }
  881.  
  882. - (void)audioRecorderDidFinishRecording:(AVAudioRecorder*)recorder successfully:(BOOL)flag
  883. {
  884. // may be called when timed audio finishes - need to stop time and reset buttons
  885. [self.timer invalidate];
  886. [self stopRecordingCleanup];
  887.  
  888. // generate success result
  889. if (flag) {
  890. NSString* filePath = [avRecorder.url path];
  891. // NSLog(@"filePath: %@", filePath);
  892. NSDictionary* fileDict = [captureCommand getMediaDictionaryFromPath:filePath ofType:@"audio/wav"];
  893. NSArray* fileArray = [NSArray arrayWithObject:fileDict];
  894.  
  895. self.pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:fileArray];
  896. } else {
  897. self.pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageToErrorObject:CAPTURE_INTERNAL_ERR];
  898. }
  899. }
  900.  
  901. - (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder*)recorder error:(NSError*)error
  902. {
  903. [self.timer invalidate];
  904. [self stopRecordingCleanup];
  905.  
  906. NSLog(@"error recording audio");
  907. self.pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageToErrorObject:CAPTURE_INTERNAL_ERR];
  908. [self dismissAudioView:nil];
  909. }
  910.  
  911. - (UIStatusBarStyle)preferredStatusBarStyle
  912. {
  913. return UIStatusBarStyleDefault;
  914. }
  915.  
  916. - (void)viewWillAppear:(BOOL)animated
  917. {
  918. if (IsAtLeastiOSVersion(@"7.0")) {
  919. [[UIApplication sharedApplication] setStatusBarStyle:[self preferredStatusBarStyle]];
  920. }
  921.  
  922. [super viewWillAppear:animated];
  923. }
  924.  
  925. @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement