Unable to get File name of image captured with camera - camera

I'm trying to build an app in which I'm able to capture image with camera and save to gallery. But I'm unable to get the file name of image. If I select image from camera roll, then I'm able to get file name of selected image.But when I capture image with camera in my app, It returns file name "null". Here is my code to save and select image from gallery using UIImagePickerController
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *chosenImage = [self scaleAndRotateImage:[info valueForKey:UIImagePickerControllerOriginalImage]];
NSString *mediaType = info[UIImagePickerControllerMediaType];
self.userProfileImage.image = chosenImage;
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
UIImage *image = info[UIImagePickerControllerOriginalImage];
if (newMedia)
UIImageWriteToSavedPhotosAlbum(image,
self,
#selector(image:finishedSavingWithError:contextInfo:),
nil);
}
imageRotation=[NSString stringWithFormat:#"%f %f %f",acos (self.userProfileImage.transform.a), asin (self.userProfileImage.transform.b), atan2(self.userProfileImage.transform.b, self.userProfileImage.transform.a)];
CGFloat angle = [(NSNumber *)[self.userProfileImage valueForKeyPath:#"layer.transform.rotation.z"] floatValue];
NSLog(#"%f", angle);
NSURL *referenceURL = [info objectForKey:UIImagePickerControllerReferenceURL];
ALAssetsLibrary *assetLibrary = [ALAssetsLibrary new];
[assetLibrary assetForURL:referenceURL
resultBlock:^(ALAsset *asset) {
ALAssetRepresentation *assetRep = [asset defaultRepresentation];
fileName = [assetRep filename];
NSLog(#"File name = %#", fileName);
}
failureBlock:^(NSError *error) {
NSLog(#"%#", error);
}];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
[[UIApplication sharedApplication] setStatusBarHidden:YES];
[picker dismissViewControllerAnimated:YES completion:nil];
imageChanged=TRUE;
}
And this code to save captured image
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
UIAlertView *alert;
//NSLog(#"Image:%#", image);
if (error) {
alert = [[UIAlertView alloc] initWithTitle:#"Error!"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
I'm stuck at the point that how can I get file name of captured image.
What wrong I'm doing in my code ? Please suggest me any correction or solution. Any help would be appreciated . Thanks in advance

Here is how I get file name of a file, video or photo, which picked with UIImagePickerController:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
#try {
self.myinfo = info;
DDLogDebug(#"MediaListView - Dismissing camera ui...");
[self.cameraUI dismissViewControllerAnimated:YES completion:nil];
mediaURL = [info objectForKey:UIImagePickerControllerMediaURL];
DDLogDebug(#"MediaListView - Media url = %#", mediaURL);
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
DDLogDebug(#"MediaListView - Selected mediaType: %#", mediaType);
// This is a video
if(mediaURL) {
DDLogDebug(#"MediaListView - This is a video");
// Just recorded video
if (self.source == UIImagePickerControllerSourceTypeCamera) {
DDLogDebug(#"MediaListView - This is a new video, saving to photos album...");
// Save video before getting its name
ALAssetsLibrary *library = [ALAssetsLibrary new];
[library writeVideoAtPathToSavedPhotosAlbum:mediaURL completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
DDLogDebug(#"MediaListView - Failed to save the photo to photos album...");
} else {
DDLogDebug(#"MediaListView - Video saved to photos album...");
// Video saved, we can get its name
[self getNameFromUrl:assetURL];
}
}];
}
else {
DDLogDebug(#"MediaListView - This is an existing video, getting name...");
// Get video name
[self getNameFromUrl:[info objectForKey:UIImagePickerControllerReferenceURL]];
}
}
// This is a photo
else {
DDLogDebug(#"MediaListView - This is a photo...");
self.originalImage = (UIImage*)[info objectForKey:UIImagePickerControllerOriginalImage];
// Just taken photo
if (self.source == UIImagePickerControllerSourceTypeCamera) {
DDLogDebug(#"MediaListView - This is a new photo, saving to photos album...");
// Save photo to album
ALAssetsLibrary *library = [ALAssetsLibrary new];
[library writeImageToSavedPhotosAlbum:[self.originalImage CGImage]
orientation:(ALAssetOrientation)[self.originalImage imageOrientation]
completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
DDLogDebug(#"MediaListView - Failed to save the vide to photos album...");
} else {
DDLogDebug(#"MediaListView - Photo saved to photos album...");
// Get photo name
[self getNameFromUrl:assetURL];
}
}];
}
else {
DDLogDebug(#"MediaListView - This is an existing image, getting name...");
// Get photo name
[self getNameFromUrl:[info objectForKey:#"UIImagePickerControllerReferenceURL"]];
}
}
}
#catch (NSException *exception) {
DDLogError(#"MediaListView - Exception in picker didFinishPickingMediaWithInfo");
DDLogError(#"MediaListView - %#", [exception description]);
}
}
- (void)getNameFromUrl(NSURL*)url {
#try {
DDLogDebug(#"MediaListView - GetNameFromUrl");
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *asset) {
if (asset == nil) {
DDLogError(#"MediaListView - SaveAssetData - asset is nil!");
return;
}
DDLogDebug(#"MediaListView - SaveAssetData - Got asset data: %#", asset.description);
ALAssetRepresentation *assetRep = [asset defaultRepresentation];
NSString *fileName = [assetRep filename];
DDLogDebug(#"MediaListView - SaveAssetData - File name = %#", fileName);
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *error) {
DDLogError(#"MediaListView - SaveAssetData - Failed to get name%#", error);
};
ALAssetsLibrary *library = [ALAssetsLibrary new];
[library assetForURL:url resultBlock:resultblock failureBlock:failureblock];
}
#catch (NSException *exception) {
DDLogError(#"MediaListView - Exception in saveAssetData");
DDLogError(#"MediaListView - %#", [exception description]);
}
}

how to get path of picture taken by camera ios swift
The image you have taken is not saved and has not any name yet. You need to save the image before you can get the path for the image. That´s why it returns nil.

Related

This item cannot be shared. Please select a different item when sharing on whatsApp

first time app install and share image is not working, it show alert:
This item cannot be shared. Please select a different item.
and I will try second time image share successfully. What is the issue?
-(void)TwitterAndmanyMore
{
UIImage * image = _imageView.image;
NSArray * items = #[image];
UIActivityViewController *controller = [[UIActivityViewController alloc]initWithActivityItems:items applicationActivities:nil];
// and present it
[self presentActivityController:controller];
}
- (void)presentActivityController:(UIActivityViewController *)controller {
// for iPad: make the presentation a Popover
controller.modalPresentationStyle = UIModalPresentationPopover;
[self presentViewController:controller animated:YES completion:nil];
UIPopoverPresentationController *popController = [controller popoverPresentationController];
popController.permittedArrowDirections = UIPopoverArrowDirectionAny;
popController.barButtonItem = self.navigationItem.leftBarButtonItem;
// access the completion handler
controller.completionWithItemsHandler = ^(NSString *activityType,
BOOL completed,
NSArray *returnedItems,
NSError *error)
{
// react to the completion
NSLog(#"----retu------%#",returnedItems);
if (completed)
{
[self showContine];
//[self viewWillAppear:YES];
// user shared an item
NSLog(#"We used activity type%#", activityType);
} else {
// user cancelled
NSLog(#"We didn't want to share anything after all.");
}
if (error) {
NSLog(#"An Error occured: %#, %#", error.localizedDescription, error.localizedFailureReason);
}
};
}
use below code for this issue it work
-(void)TwitterAndmanyMore
{
// UIImage * image = _imageView.image;
// NSLog(#"Image Data %#",image);
// NSArray * items = #[#"", image];
tempImage = [UIImage imageNamed:#"Sample.jpg"];
tempImage = _imageView.image;
NSString *theMessage = #"";
NSArray *items;
CGImageRef cgref = [tempImage CGImage];
CIImage *cim = [tempImage CIImage];
if (cim != nil || cgref != NULL)
{
items = #[theMessage,tempImage];
}
else
{
items = #[theMessage];
}
NSLog(#"Image Data %#",items);
// build an activity view controller
UIActivityViewController *controller = [[UIActivityViewController alloc]initWithActivityItems:items applicationActivities:nil];
// and present it
[self presentActivityController:controller];
}
- (void)presentActivityController:(UIActivityViewController *)controller {
// for iPad: make the presentation a Popover
controller.modalPresentationStyle = UIModalPresentationPopover;
[self presentViewController:controller animated:YES completion:nil];
UIPopoverPresentationController *popController = [controller popoverPresentationController];
popController.permittedArrowDirections = UIPopoverArrowDirectionAny;
popController.barButtonItem = self.navigationItem.leftBarButtonItem;
// access the completion handler
controller.completionWithItemsHandler = ^(NSString *activityType,
BOOL completed,
NSArray *returnedItems,
NSError *error)
{
// react to the completion
NSLog(#"----retu------%#",returnedItems);
if (completed)
{
[self showContine];
//[self viewWillAppear:YES];
// user shared an item
NSLog(#"We used activity type%#", activityType);
} else {
// user cancelled
NSLog(#"We didn't want to share anything after all.");
}
if (error) {
NSLog(#"An Error occured: %#, %#", error.localizedDescription, error.localizedFailureReason);
}
};
}

Text To Speech And Speech To Text Recognition -->self - Recognition is occurring

I want to developing an app which should support speech to text and text to speech ,
i)Speech to Text- Procedure-i have used Speech framework for speech to text ,whenever i open a app and if i start speaking ,the app should recognize the voice and should convert the speech into text .This is working
ii)Text to Speech - Procedure -i have used AVFoundation and MediaPlayer library If user press the play button it should convert the text i.e,whatever appear in the screen into speech.Working now .
Here is the problem is am facing
while processing text to speech ,the speech recognizer recognizes the playing voice and printing the words again in textbox.
Example- if i say "Hello Good Morning" it is printing in text box and then if i press a play button it is playing a voice Hello Good Morning but at this time speech to text recognize recognize this voice i mean self- recognition and it's printing "Hello Good Morning Hello Good Morning"
I want to stop the Speech To Text Process while processing the Text To Speech
For this , i have stopped speech recognition request while playing the speech
here is the code,
#implementation ViewController
{
SFSpeechAudioBufferRecognitionRequest *recognitionRequest;
SFSpeechRecognitionTask *recognitionTask;
AVAudioEngine *audioEngine;
NSMutableArray *speechStringsArray;
BOOL SpeechToText;
NSString* resultString;
NSString *str ;
NSString *searchString;
NSString *textToSpeak;
}
- (void)viewDidLoad {
[super viewDidLoad];
//Speech To Text ****
speechStringsArray = [[NSMutableArray alloc]init];
// Initialize background audio session
NSError *error = NULL;
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:&error];
if(error) {
NSLog(#"#error: %#", error);
}
[session setActive:YES error:&error];
if (error) {
NSLog(#"#error: %#", error);
}
// Enabled remote controls
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
// Voice setup
self.voicePicker.delegate = self;
self.voice = [AVSpeechSynthesisVoice voiceWithLanguage:#"en-us"];
self.voices = [NSMutableArray arrayWithObjects:
#{#"voice" : #"en-us", #"label" : #"American English (Female)"},
#{#"voice" : #"en-au", #"label" : #"Australian English (Female)"},
#{#"voice" : #"en-gb", #"label" : #"British English (Male)"},
#{#"voice" : #"en-ie", #"label" : #"Irish English (Female)"},
#{#"voice" : #"en-za", #"label" : #"South African English (Female)"},
nil];
// Synthesizer setup
self.synthesizer = [[AVSpeechSynthesizer alloc] init];
self.synthesizer.delegate = self;
// UITextView delegate
self.textView.delegate = self;
// This notifcation is generated from the AppDelegate applicationDidBecomeActive method to make sure that if the play or pause button is updated in the background then the button will be updated in the toolbar
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(updateToolbar) name:#"updateToolbar" object:nil];
}
-(void)viewDidAppear:(BOOL)animated
{
self.speechRecognizer = [[SFSpeechRecognizer alloc]initWithLocale:[NSLocale localeWithLocaleIdentifier:#"en-US en-UK"]];
self.speechRecognizer.delegate = self;
audioEngine = [[AVAudioEngine alloc]init];
[SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus authStatus) {
switch (authStatus) {
case SFSpeechRecognizerAuthorizationStatusAuthorized:
//User gave access to speech recognition
NSLog(#"Authorized");
[self start_record];
break;
case SFSpeechRecognizerAuthorizationStatusDenied:
//User denied access to speech recognition
NSLog(#"AuthorizationStatusDenied");
break;
case SFSpeechRecognizerAuthorizationStatusRestricted:
//Speech recognition restricted on this device
NSLog(#"AuthorizationStatusRestricted");
break;
case SFSpeechRecognizerAuthorizationStatusNotDetermined:
//Speech recognition not yet authorized
break;
default:
NSLog(#"Default");
break;
}
}];
//MARK : Interface Builder Actions
}
****coding for increase the speed and pitch****
- (IBAction)handleSpeedStepper:(UIStepper *)sender
{
double speedValue = self.speedStepper.value;
[self.speedValueLabel setText:[NSString stringWithFormat:#"%.1f", speedValue]];
}
- (IBAction)handlePitchStepper:(UIStepper *)sender
{
double pitchValue = self.pitchStepper.value;
[self.pitchValueLabel setText:[NSString stringWithFormat:#"%.1f", pitchValue]];
}
//Play button for text to speech
- (IBAction)handlePlayPauseButton:(UIBarButtonItem *)sender
{
if (self.synthesizer.speaking && !self.synthesizer.paused) {
if (self.pauseSettingSegmentedControl.selectedSegmentIndex == 0) {
// Stop immediately
[self.synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];
}
else {
// Stop at end of current word
[self.synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryWord];
}
[self updateToolbarWithButton:#"play"];
}
else if (self.synthesizer.paused) {
[self.synthesizer continueSpeaking];
[self updateToolbarWithButton:#"pause"];
}
else {
[self speakUtterance];
[self updateToolbarWithButton:#"pause"];
}
}
//method for speech to text
-(void)start_record{
NSError * outError;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&outError];
[audioSession setMode:AVAudioSessionModeMeasurement error:&outError];
[audioSession setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:&outError];
recognitionRequest = [[SFSpeechAudioBufferRecognitionRequest alloc]init];
AVAudioInputNode *inputNode = audioEngine.inputNode;
if (recognitionRequest == nil) {
NSLog(#"Unable to created a SFSpeechAudioBufferRecognitionRequest object");
}
if (inputNode == nil) {
NSLog(#"Audio engine has no input node ");}
//configure request so that results are returned before audio recording is finished
[recognitionRequest setShouldReportPartialResults:YES];
// A recognition task represents a speech recognition session.
//We keep a reference to the task so that it can be cancelled .
recognitionTask = [self.speechRecognizer recognitionTaskWithRequest:recognitionRequest resultHandler:^(SFSpeechRecognitionResult * result, NSError * error1) {
BOOL isFinal = false;
if ((result = result)) {
NSString *speech = result.bestTranscription.formattedString;
NSLog(#"the speech:%#",speech);
// coding for fixing append string issue
for (int i = 0 ;i <speechStringsArray.count;i++)
{
str = [speechStringsArray objectAtIndex:i];
NSRange range = [speech rangeOfString:str options:NSCaseInsensitiveSearch];
NSLog(#"found: %#", (range.location != NSNotFound) ? #"Yes" : #"No");
if (range.location != NSNotFound) {
resultString = [speech stringByReplacingCharactersInRange:range withString:#""];
speech = resultString;
NSLog(#" the result is : %#",resultString);
}
}
//specific functions - space for second word
if (resultString.length>0) {
self.textView.text = [NSString stringWithFormat:#"%#%#",self.textView.text,resultString];
[speechStringsArray addObject:resultString]; }
//specific function space for first word -Working fine
else
{
[speechStringsArray addObject:speech];
self.textView.text = speech;
}
}
NSLog(#" array %#",speechStringsArray);
isFinal = result.isFinal;
}
if (error1 != nil || isFinal) {
[audioEngine stop];
[inputNode removeTapOnBus:0];
recognitionRequest = nil;
recognitionTask = nil;
[self start_record];
}}];
AVAudioFormat *recordingFormat = [inputNode outputFormatForBus:0];
[inputNode installTapOnBus:0 bufferSize:1024 format:recordingFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when){
[recognitionRequest appendAudioPCMBuffer:buffer];}
];
NSError *error1;
[audioEngine prepare];
[audioEngine startAndReturnError:&error1];}
- (void)speakUtterance
{
NSLog(#"speakUtterance");
didStartSpeaking = NO;
textToSpeak = [NSString stringWithFormat:#"%#", self.textView.text];
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:textToSpeak];
utterance.rate = self.speedStepper.value;
utterance.pitchMultiplier = self.pitchStepper.value;
utterance.voice = self.voice;
[self.synthesizer speakUtterance:utterance];
[self displayBackgroundMediaFields];
}
- (void)displayBackgroundMediaFields
{
MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:#"Play"]];
NSDictionary *info = #{ MPMediaItemPropertyTitle: self.textView.text,
MPMediaItemPropertyAlbumTitle: #"TextToSpeech App",
MPMediaItemPropertyArtwork: artwork};
[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = info;
}
- (void)updateToolbar
{
if (self.synthesizer.speaking && !self.synthesizer.paused) {
[self updateToolbarWithButton:#"pause"];
}
else {
[self updateToolbarWithButton:#"play"];
}}
- (void)updateToolbarWithButton:(NSString *)buttonType
{
//stopping the speech to text process
if (audioEngine.isRunning) {
[audioEngine stop];
[recognitionRequest endAudio];
}
NSLog(#"updateToolbarWithButton: %#", buttonType);
UIBarButtonItem *audioControl;
if ([buttonType isEqualToString:#"play"]) {
// Play
audioControl = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:#selector(handlePlayPauseButton:)];
}
else {
// Pause
audioControl = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemPause target:self action:#selector(handlePlayPauseButton:)];
}
UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[self.toolbar setItems:#[flexibleItem, audioControl, flexibleItem]];
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent
{
NSLog(#"receivedEvent: %#", receivedEvent);
if (receivedEvent.type == UIEventTypeRemoteControl) {
switch (receivedEvent.subtype) {
case UIEventSubtypeRemoteControlPlay:
NSLog(#"UIEventSubtypeRemoteControlPlay");
if (self.synthesizer.speaking) {
[self.synthesizer continueSpeaking];
}
else {
[self speakUtterance];
}
break;
case UIEventSubtypeRemoteControlPause:
NSLog(#"pause - UIEventSubtypeRemoteControlPause");
if (self.pauseSettingSegmentedControl.selectedSegmentIndex == 0) {
// Pause immediately
[self.synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];
}
else {
// Pause at end of current word
[self.synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryWord];
}
break;
case UIEventSubtypeRemoteControlTogglePlayPause:
if (self.synthesizer.paused) {
NSLog(#"UIEventSubtypeRemoteControlTogglePlayPause");
[self.synthesizer continueSpeaking];
}
else {
NSLog(#"UIEventSubtypeRemoteControlTogglePlayPause");
if (self.pauseSettingSegmentedControl.selectedSegmentIndex == 0) {
// Pause immediately
[self.synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];
}
else {
// Pause at end of current word
[self.synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryWord];
}
}
break;
case UIEventSubtypeRemoteControlNextTrack:
NSLog(#"UIEventSubtypeRemoteControlNextTrack - appropriate for playlists");
break;
case UIEventSubtypeRemoteControlPreviousTrack:
NSLog(#"UIEventSubtypeRemoteControlPreviousTrack - appropriatefor playlists");
break;
default:
break;
}
}
}
pragma mark UIPickerViewDelegate Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return self.voices.count;
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
UILabel *rowLabel = [[UILabel alloc] init];
NSDictionary *voice = [self.voices objectAtIndex:row];
rowLabel.text = [voice objectForKey:#"label"];
return rowLabel;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:(NSInteger)component
{
NSDictionary *voice = [self.voices objectAtIndex:row];
NSLog(#"new picker voice selected with label: %#", [voice objectForKey:#"label"]);
self.voice = [AVSpeechSynthesisVoice voiceWithLanguage:[voice objectForKey:#"voice"]];
}
pragma mark SpeechSynthesizerDelegate methods
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance
{
// This is a workaround of a bug. When we change the voice the first time the speech utterence is set fails silently. We check that the method willSpeakRangeOfSpeechString is called and set didStartSpeaking to YES there. If this method is not called (silent fail) then we simply request to speak again.
if (!didStartSpeaking) {
[self speakUtterance];
}
else {
[self updateToolbarWithButton:#"play"];
NSLog(#"the text are:%#",self.textView.text);
}}
- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer willSpeakRangeOfSpeechString:(NSRange)characterRange utterance:(AVSpeechUtterance *)utterance
{
didStartSpeaking = YES;
//[self setTextViewTextWithColoredCharacterRange:characterRange];
}
#pragma mark UITextViewDelegate Methods
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if([text isEqualToString:#"\n"]) {
[textView resignFirstResponder];
return NO;
}
return YES;
}
Dont initialize all the things in the ViewDidLoad. When You tap on button to convert text to speech, at that that time make the speech to text conversion object as nil also set the delegate the nil. Same things for the vice versa also.

How to record video from iPhone camera in iOS 9 objective c?

hello I need to build app that record video from iPhone camera.
I search in the net and not found notting that works in iOS 9.
I get this code from this git project :
https://github.com/versluis/Video-Recorder
This code open camera but not allow Me to take a video.
- (IBAction)recordButton:(id)sender {
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIImagePickerController *picker = [[UIImagePickerController alloc]init];
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.delegate = self;
picker.allowsEditing = NO;
NSArray *mediaTypes = [[NSArray alloc]initWithObjects:(NSString *)kUTTypeMovie, nil];
picker.mediaTypes = mediaTypes;
[self presentViewController:picker animated:YES completion:nil];
} else {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:#"I'm afraid there's no camera on this device!" delegate:nil cancelButtonTitle:#"Dang!" otherButtonTitles:nil, nil];
[alertView show];
}
}
- (IBAction)playbackButton:(id)sender {
// pick a video from the documents directory
NSURL *video = [self grabFileURL:#"video.mov"];
// create a movie player view controller
MPMoviePlayerViewController * controller = [[MPMoviePlayerViewController alloc]initWithContentURL:video];
[controller.moviePlayer prepareToPlay];
[controller.moviePlayer play];
// and present it
[self presentMoviePlayerViewControllerAnimated:controller];
}
#pragma mark - Delegate Methods
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
// user hit cancel
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// grab our movie URL
NSURL *chosenMovie = [info objectForKey:UIImagePickerControllerMediaURL];
// save it to the documents directory
NSURL *fileURL = [self grabFileURL:#"video.mov"];
NSData *movieData = [NSData dataWithContentsOfURL:chosenMovie];
[movieData writeToURL:fileURL atomically:YES];
// save it to the Camera Roll
UISaveVideoAtPathToSavedPhotosAlbum([chosenMovie path], nil, nil, nil);
// and dismiss the picker
[self dismissViewControllerAnimated:YES completion:nil];
}
- (NSURL*)grabFileURL:(NSString *)fileName {
// find Documents directory
NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
// append a file name to it
documentsURL = [documentsURL URLByAppendingPathComponent:fileName];
return documentsURL;
}
Ray gave pretty good tutorial about this. Hope it helped.

Coding Multiple Leaderboards

I am making a game in which the player can achieve a positive high score or a negative low score depending on the choices they make. The high score has been working fine, but I'm having trouble with the low score.
-(void)authenticateLocalPlayer{
GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
localPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error){
if (viewController != nil) {
[self presentViewController:viewController animated:YES completion:nil];
}
else{
if ([GKLocalPlayer localPlayer].authenticated) {
_gameCenterEnabled = YES;
// Get the default leaderboard identifier.
[[GKLocalPlayer localPlayer] loadDefaultLeaderboardIdentifierWithCompletionHandler:^(NSString *leaderboardIdentifier, NSError *error) {
if (error != nil) {
NSLog(#"%#", [error localizedDescription]);
}
else{
_leaderboardIdentifier = leaderboardIdentifier;
}
}];
}
else{
_gameCenterEnabled = NO;
}
}
};
}
-(void)reportScore{
GKScore *highscore = [[GKScore alloc] initWithLeaderboardIdentifier:_leaderboardIdentifier];
highscore.value = HighScoreNumber;
[GKScore reportScores:#[highscore] withCompletionHandler:^(NSError *error) {
if (error != nil) {
NSLog(#"%#", [error localizedDescription]);
}
}];
-(void)showLeaderboardAndAchievements:(BOOL)shouldShowLeaderboard{
GKGameCenterViewController *gcViewController = [[GKGameCenterViewController alloc] init];
gcViewController.gameCenterDelegate = self;
if (shouldShowLeaderboard) {
gcViewController.viewState = GKGameCenterViewControllerStateLeaderboards;
gcViewController.leaderboardIdentifier = _leaderboardIdentifier;
}
else{
gcViewController.viewState = GKGameCenterViewControllerStateAchievements;
}
[self presentViewController:gcViewController animated:YES completion:nil];
}
You'll notice leaderboardidentifier, it is useful for reporting scores to the default leaderboard, but when I try to get it to work for two different ones, the code shuts down.
I've tried adding this to "Report Score":
GKScore *lowscore = [[GKScore alloc] initWithLeaderboardIdentifier:_leaderboardIdentifier];
lowscore.value = LowScoreNumber;
[GKScore reportScores:#[lowscore] withCompletionHandler:^(NSError *error) {
if (error != nil) {
NSLog(#"%#", [error localizedDescription]);
}
}];
}
Then, I change the leaderboard identifiers to match itunesconnect, but I'm not sure how I need to change authenticateLocalPlayer and shouldShowLeaderboardandAchievements.
I have some experience with game center. I have two games on the App Store that have multiple leaderboards (Squared!! and Primes!).
Instead of having one method for each leaderboard I made one method for submitting scores. Here is that method:
-(void) submitScore:(int64_t)score Leaderboard: (NSString*)leaderboard
{
//1: Check if Game Center
// features are enabled
if (!_gameCenterFeaturesEnabled) {
return;
}
//2: Create a GKScore object
GKScore* gkScore =
[[GKScore alloc]
initWithLeaderboardIdentifier:leaderboard];
//3: Set the score value
gkScore.value = score;
//4: Send the score to Game Center
[gkScore reportScoreWithCompletionHandler:
^(NSError* error) {
[self setLastError:error];
BOOL success = (error == nil);
if ([_delegate
respondsToSelector:
#selector(onScoresSubmitted:)]) {
[_delegate onScoresSubmitted:success];
}
}];
}
When you want to submit your high scores all you have to do is add something like:
[[GCHelper sharedGameKitHelper] submitScore:myLowScore Leaderboard:TELS];
[[GCHelper sharedGameKitHelper] submitScore:myHighScore Leaderboard:TEHS];
GCHelper is the class that contains my submitScore:Leaderboard: method.
To view your leaderboards or achievements within your app try this:
- (void) presentLeaderboards {
GKGameCenterViewController* gameCenterController = [[GKGameCenterViewController alloc] init];
gameCenterController.viewState = GKGameCenterViewControllerStateLeaderboards;
gameCenterController.gameCenterDelegate = self;
[self presentViewController:gameCenterController animated:YES completion:nil];
}
- (void) gameCenterViewControllerDidFinish:(GKGameCenterViewController*) gameCenterViewController {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void) presentAchievements {
GKGameCenterViewController* gameCenterController = [[GKGameCenterViewController alloc] init];
gameCenterController.viewState = GKGameCenterViewControllerStateAchievements;
gameCenterController.gameCenterDelegate = self;
I hope this answers your question!

Can't play system sounds after capturing audio / video

I'm recoding audio/video using AVfoudnation. and I need to play a sounds, using system sounds, before I start capturing video/audio. This is working correctly the first time, but when I try to do it the second time, the system audi doesn't play. My guess is that something in the AVfoundation is not been released correctly.
In my application deletage, I have this code in the applicationDidFinishLaunching method:
VKRSAppSoundPlayer *aPlayer = [[VKRSAppSoundPlayer alloc] init];
[aPlayer addSoundWithFilename:#"sound1" andExtension:#"caf"];
self.appSoundPlayer = aPlayer;
[aPlayer release];
and also this method
- (void)playSound:(NSString *)sound
{
[appSoundPlayer playSound:sound];
}
As you can see I'm using VKRSAppSoundPlayer, which works great!
In a view, I have this code:
- (void) startSession
{
self.session = [[AVCaptureSession alloc] init];
[session beginConfiguration];
if([session canSetSessionPreset:AVCaptureSessionPreset640x480])
session.sessionPreset = AVCaptureSessionPresetMedium;
[session commitConfiguration];
CALayer *viewLayer = [videoPreviewView layer];
AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
captureVideoPreviewLayer.frame = viewLayer.bounds;
[viewLayer addSublayer:captureVideoPreviewLayer];
self.videoInput = [AVCaptureDeviceInput deviceInputWithDevice:[self frontFacingCameraIfAvailable] error:nil];
self.audioInput = [AVCaptureDeviceInput deviceInputWithDevice:[self audioDevice] error:nil];
if(videoInput){
self.videoOutput = [[AVCaptureMovieFileOutput alloc] init];
[session addOutput:videoOutput];
//[videoOutput release];
if([session canAddInput:videoInput]){
//[session beginConfiguration];
[session addInput:videoInput];
}
//[videoInput release];
[session removeInput:[self audioInput]];
if([session canAddInput:audioInput]){
[session addInput:audioInput];
}
//[audioInput release];
if([session canAddInput:audioInput])
[session addInput:audioInput];
NSLog(#"startRunning!");
[session startRunning];
[self startRecording];
if(![self recordsVideo])
[self showAlertWithTitle:#"Video Recording Unavailable" msg:#"This device can't record video."];
}
}
- (void) stopSession
{
[session stopRunning];
[session release];
}
- (AVCaptureDevice *)frontFacingCameraIfAvailable
{
NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
AVCaptureDevice *captureDevice = nil;
Boolean cameraFound = false;
for (AVCaptureDevice *device in videoDevices)
{
NSLog(#"1 frontFacingCameraIfAvailable %d", device.position);
if (device.position == AVCaptureDevicePositionBack){
NSLog(#"1 frontFacingCameraIfAvailable FOUND");
captureDevice = device;
cameraFound = true;
break;
}
}
if(cameraFound == false){
for (AVCaptureDevice *device in videoDevices)
{
NSLog(#"2 frontFacingCameraIfAvailable %d", device.position);
if (device.position == AVCaptureDevicePositionFront){
NSLog(#"2 frontFacingCameraIfAvailable FOUND");
captureDevice = device;
break;
}
}
}
return captureDevice;
}
- (AVCaptureDevice *) audioDevice
{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
if ([devices count] > 0) {
return [devices objectAtIndex:0];
}
return nil;
}
- (void) startRecording
{
#if _Multitasking_
if ([[UIDevice currentDevice] isMultitaskingSupported]) {
[self setBackgroundRecordingID:[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{}]];
}
#endif
[videoOutput startRecordingToOutputFileURL:[self generatenewVideoPath]
recordingDelegate:self];
}
- (void) stopRecording
{
[videoOutput stopRecording];
}
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
fromConnections:(NSArray *)connections error:(NSError *)error
{
NSFileManager *man = [[NSFileManager alloc] init];
NSDictionary *attrs = [man attributesOfItemAtPath: [outputFileURL path] error: NULL];
NSString *fileSize = [NSString stringWithFormat:#"%llu", [attrs fileSize]];
// close this screen
[self exitScreen];
}
-(BOOL)recordsVideo
{
AVCaptureConnection *videoConnection = [AVCamUtilities connectionWithMediaType:AVMediaTypeVideo
fromConnections:[videoOutput connections]];
return [videoConnection isActive];
}
-(BOOL)recordsAudio
{
AVCaptureConnection *audioConnection = [AVCamUtilities connectionWithMediaType:AVMediaTypeAudio
fromConnections:[videoOutput connections]];
return [audioConnection isActive];
}
If I do [videoInput release]; and [audioInput release]; I got a bad access error. that's why they are commented out. This may be part of the issue.
If I try to play the system sound n times, it work, but if I go first to the recording script, it wont work after that.
Any ideas?
The proper way to release AVCaptureSession is the following:
- (void) destroySession {
// Notify the view that the session will end
if ([delegate respondsToSelector:#selector(captureManagerSessionWillEnd:)]) {
[delegate captureManagerSessionWillEnd:self];
}
// remove the device inputs
[session removeInput:[self videoInput]];
[session removeInput:[self audioInput]];
// release
[session release];
// remove AVCamRecorder
[recorder release];
// Notify the view that the session has ended
if ([delegate respondsToSelector:#selector(captureManagerSessionEnded:)]) {
[delegate captureManagerSessionEnded:self];
}
}
If you're having some sort of release problems (bad access), I can recommend taking your code out of your current "messy" project to some other new project and debug the problem over there.
When I had similar problem, I just did that. I shared it on Github, you might find this project useful: AVCam-CameraReleaseTest