Reopening AVCaptureSession - iphone

I have an application which takes some pictures.
My whole application is based on the AVCam sample code from WWDC 2010.
I've messed with it a lot and yet, up until now I can't figure out how to release the camera view properly which releases the camera session...
All i'm trying to do is the following:
Open camera view controller
Take some photos
Close camera view Controller
Open it again
The second time I push the viewController the session is lost, preview is not available and capturing is not available as well. I've published full example code on github.
My workaround for the issue was not to release the camera at all so the Camera View Controller acts as a Singleton, which I think is not the right way. moreover, with this behavior I couldn't figure out a way to support camera when application went to the background (phone call for example).
Please advice. How do I destruct the camera session? and is it important to do so?

I've added the following message to AVCamCaptureManager
- (void) destroySession {
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];
if ([delegate respondsToSelector:#selector(captureManagerSessionEnded:)]) {
[delegate captureManagerSessionEnded:self];
}
}
I'm calling destroySession when the viewController holding the camera get close (on my example it's -closeCamera: of AVCamViewController).
For the full working example, you're welcome to download AVCam-CameraReleaseTest on github.com

G
I think that may help you have a look .
http://red-glasses.com/index.php/tutorials/ios4-take-photos-with-live-video-preview-using-avfoundation/

Related

How to handle a system alert message for iOS?

I have an app where i am using UIImagePickerController to use the native camer inorder to click pictures but the when the photo gallery on the device is full. I get a alert message which says "Cannot Take Photo - There is not enough available storage to take a photo.You can manage your storage in Settings". I am given two options to click the "Done" button or "Settings" button. Clicking either of them does nothing and the app freezes completely.
This is what i get from the console logs
Not enough space to take a picture. Available space is 0
The code for the picker
UIImagePickerController *mediaPicker = [[UIImagePickerController alloc] init];
mediaPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
mediaPicker.delegate=self;
mediaPicker.sourceType=UIImagePickerControllerSourceTypeCamera;
[self presentModalViewController:mediaPicker animated:YES];
I have implemented and tried all the delegates already and its not calling any delegate.
Is there any way i can implement something where i can use a listener to detect when this error occurs and take back the user to the previous screen ?
Sounds like your device run out of memory, system sent lots of "Out of Memory" notifications and your app got one, too. As result your app released the UIViewController, which originally launched UIImagePickerController.
Now when you dismiss imagePicker with Done/Settings button, control returns back to your app. The old UIViewController doesn't exist any more and you haven't implemented code to recreate it from scratch in this kind of situations. The device looks like it frozen, but only because UI wasn't redrawn by your app. Otherwise app works just fine.
You can check this case by implementing didReceiveMemoryWarning method into every UIViewController and logging, if it's called:
- (void)didReceiveMemoryWarning
{
NSLog(#"%#", [self description]);
[super didReceiveMemoryWarning];
}
One of my favourite bugs. Easy to miss :)
This sounds like a bug in iOS.
You should file a feedback at https://feedbackassistant.apple.com/.

Keyboard shows then immediately hides itself when showing MFMessageComposeViewController

I am building a PhoneGap app using Cordova 2.2 for IOS. I am experiencing some bizarre behavior when calling out to a native obj-c plugin I have written to show the MFMessageComposeViewController.
The setup is very simple - I have a tap event attached to a UI element, that when pressed, will make a call to my PhoneGap plugin, pass with it a number and a text message, then show the MFMessageComposeViewController with the parameters pre-populated.
My javascript looks like this:
$(document).bind('deviceready', function(){
$(".theButton").tap(function(){
cordova.exec(function(){}, function() {}, "PhoneGapSms", "SendSms", [db.getItem("profile_sms"), db.getItem("profile_emergency")]);
});
});
And my obj-c code looks like this:
- (void)SendSms:(CDVInvokedUrlCommand*)command
{
CDVInvokedUrlCommand* myCommand = command;
MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
NSString* body = [command.arguments objectAtIndex:0];
NSString* toRecipientsString = [command.arguments objectAtIndex:1];
if(body != nil)
picker.body = body;
if(toRecipientsString != nil)
[picker setRecipients:[ toRecipientsString componentsSeparatedByString:#","]];
picker.messageComposeDelegate = self;
[self.viewController presentModalViewController:picker animated:YES];
[[UIApplication sharedApplication] setStatusBarHidden:YES];
[picker release];
}
So, all in all, very simple stuff.
My Problem is this:
When my iPhone is plugged into my Mac and the app is run from XCode, the Message Composer overlay appears great, with my values pre-populated. Image below demonstrating the SMS interface appears fine while plugged into XCode:
When my iPhone is unplugged from my Mac, and the app is run from the spring board, the Overlay slides up, the keyboard begins to slide up, then immediately slides down - making it impossible to type or send the message. This is what it looks like when not attached to the Mac/Xcode - the keyboard begins to slide up then immediately slides down (~ < 1 sec) leaving the following interface:
I can't for the life of me figure out what would cause the keyboard to hide when not running from XCode, but work perfectly well when it is.
Is there any way to 'force' the keyboard to display, or possibly put the whole modalviewcontroller as first responder in some form or fashion?
Any suggestions are appreciated!
Edit:
The keyboard WILL appear again if you click in the contact area
You must add MessageUI.framework to your Xcode project and include a
#import <MessageUI/MessageUI.h> in your header file.
try this code may be its helpful to you..
[self presentModalViewController:picker animated:YES];
//[self becomeFirstResponder];//try picker also instead of self
Also Refer this bellow tutorial and also check demo..
new-tutorial-developing-and-architecting-a-phonegap-application
SMSComposer
i hope this help you...
I encountered these symptoms with a Sencha Touch 2.2 and Cordova 2.6.0 setup (specifically, iOS 6+ devices).
The issue was with the web framework stealing focus away from the native SMS Composer modal, typically occurring after the first SMS Composer modal had been successfully displayed and closed.
A event.preventDefault() and event.stopPropagation() call once the event had been fired (or event.stopEvent() in Sencha land) resolved this.
Hope this helps,
-James
First: The most likely culprit, without seeing your code, is that your parent (presenting) view controller may have an action in its viewWillDisappear or viewDidDisappear that is affecting who has the "first" responder. These methods get called when presenting a view controller modally. It may be behaving differently on the simulator than the device due to timing - often really close timing conditions are different on the ARM device and the i386 processor.
Second: Does anywhere in your app register for the UIKeyboardWillShowNotification or the UIKeyboardDidShowNotification? If so, put breakpoints in the methods that are called as a result - it's possible some other controller in your view hierarchy is interfering with this one.
To answer your question...
Is there any way to 'force' the keyboard to display, or possibly put the whole modalviewcontroller as first responder in some form or fashion?
No to both. The only way to make the keyboard display is to call the becomeFirstResponder method of the input view. Since Apple doesn't expose the text view, you cannot send it messages. Setting the modalViewController as first responder would be setting the wrong object.
I found the same type of issue But Not Sure it will Solve your problem or not Just Have a Look on the Following Links :
1. http://community.phonegap.com/nitobi/topics/keyboard_is_not_triggerd_in_my_ios_build
2. https://github.com/phonegap/build/issues/31
If its not Solving your issue then you can Download the Sample code Here.
Link: https://github.com/phonegap/phonegap-plugins/tree/master/iPhone/SMSComposer

Use MPMediaPicker selections as AVAudioPlayer inputs

I'm programming an application for the hearing-impaired. I'm hoping to take tracks from the iTunes library, and in my app have a slider for panning. I don't want to use OpenAL (this isn't a game - I repeat this is a media player). So since AVAudioPlayer has the easy pan method, can I take selections from the MPMediaPicker and feed them into the AVAudioPlayer so I can pan them?
I dont do a lot of iOS development, but I believe there are two ways.
Method #1
You need to add /System/Library/Frameworks/AVFoundation.framework to your target in Xcode and #import AVAudioPlayer.h as well as You need to add MediaPlayer.framework to your target in Xcode and #import .
For this operation, you need MPMediaPicker to pass the song data to AVAMedia Player. That can be accomplished like this:
#interface MusicPlayerDemoViewController : UIViewController <MPMediaPickerControllerDelegate> {
...
}
...
// This action should open the media picker
- (IBAction)openMediaPicker:(id)sender;
#end
// MusicPlayerDemoViewController.m
- (IBAction)openMediaPicker:(id)sender {
MPMediaPickerController *mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeMusic];
mediaPicker.delegate = self;
mediaPicker.allowsPickingMultipleItems = NO; // this is the default
[self presentModalViewController:mediaPicker animated:YES];
[mediaPicker release];
}
// Media picker delegate methods
- (void)mediaPicker: (MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection {
// We need to dismiss the picker
[self dismissModalViewControllerAnimated:YES];
(Code Continues Below, the blanks are for you to fill in)
AT THIS POINT, CALL THE AVAAUDIOPLAYER CLASS AND TELL IT TO PLAY mediaItemCollection . REMEMBER TO STOP AUDIO BEFORE PLAYING, AS IT WILL PLAY MULTIPLE SONGS AT ONCE.
}
- (void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker {
// User did not select anything
// We need to dismiss the picker
[self dismissModalViewControllerAnimated:YES];
}
NOW, ONCE THIS IS DONE THE USER NEEDS TO SELECT A NEW SONG. YOU COULD EITHER CREATE A WHILE LOOP AROUND THE WHOLE THING, WHERE THE CONDITIONAL IS CURRENT TIME >= DURATION (FROM AVAAUDIO PLAYER),
ALTERNATIVELY, YOU COULD CREATE A BUTTON TO OPEN THE PICKER
For more questions checkout:
http://oleb.net/blog/2009/07/the-music-player-framework-in-the-iphone-sdk/ (I used much of their code)
http://developer.apple.com/library/ios/#DOCUMENTATION/AVFoundation/Reference/AVAudioPlayerClassReference/Reference/Reference.html
Good Luck!
Derek
Try having AVAMediaPlayer play the variable mediaItemCollection. This was assigned by the picker to be the song location by the code above. If this does not work make sure that AVAMediaPlayer uses the same input variable type (format, like an ID or a folder location) as MpMediaPicker.
That error message sounds like a technical issue. The only thing I can think of is that AVAAudio player or MPmedia player is looking for a Volume variable (it is required?) and can't find one. I can't really answer this one as I don't do iPhone Development, try there forums or website for some help.
Sounds like you are doing a good job! If you are interested, (I don't know if you are staying at DA) Mr. Cochran (the dean of students at the Upper School) is teaching a iPhone Development Class and a AP Computer Science Class (I am in). If you want to take it further, or you want to just ask questions I know he is more than happy too!
Good Luck! Tell me when it is finished so I can test the results!

iOS 4: Remote controls for background audio

I'm currently attempting to set up background audio for an app I'm developing for iOS 4. The app doesn't have a dedicated music player viewController, however, unlike other background audio apps such as Pandora, which makes the task a bit more confusing.
I've set the appropriate Info.plist settings correctly and have an AVAudioPlayer object in my app delegate which is accessible from everywhere. When the user plays a song, I replace the AVAudioPlayer with a new one initialized with the song and play it. This all works great, except now I have no idea how to go about supporting remote control events.
Based on Apple's documentation, I have this:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
switch(event.subtype) {
case UIEventSubtypeRemoteControlTogglePlayPause:
if([iPhoneAppDelegate backgroundAudioPlayer].playing)
[iPhoneAppDelegate pauseBackgroundAudioPlayer];
else
[iPhoneAppDelegate playBackgroundAudioPlayer];
break;
}
}
The thing is, where do I put this? Apple's documentation seems to suggest this should go in some view controller somewhere, but my app has lots of view controllers and navigation controllers. Wherever I try to put this, for some reason tapping the Toggle Play/Pause button in the multitasking tray remote controls either causes the song to just pause for a moment and then unpause, or somehow causes the song to play twice.
The documentation examples are a bit misleading, but there is no need to subclass anything anywhere. The correct place to put remoteControlReceivedWithEvent: is in the application delegate, as it remains in the responder chain regardless of whether the app is in the foreground or not. Also the begin/end receiving remote control events should be based on whether you actually need the events, not on the visibility of some random view.
I found a couple of solutions to receiving global remote control events on the Apple Developer Forums after a bit of searching.
One way is to subclass UIWindow and override its remoteControlReceivedWithEvent:.
The second, perhaps nicer way is to subclass UIApplication and override sendEvent:. That way, you can intercept all the remote control events and handle them there globally, and not have any other responders handle them later in the responder chain.
- (void)sendEvent:(UIEvent *)event {
if (event.type == UIEventTypeRemoteControl) {
// Handle event
}
else
[super sendEvent:event];
}
The second method didn't work for me, sendEvent was never called. However the first method worked just nicely (subclassing UIWindow).
I struggled with this one for a while and none of the answers above worked. The bug in my code, and I hope that it will help someone reading this, was that I had the AudioSession set to mix with others. You want to be the foreground audio player to get Remote Control events. Check to see if you have INCORRECT code like this:
[[AVAudioSession sharedInstance] setDelegate: self];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
UInt32 doSetProperty = 0;
AudioSessionSetProperty (
kAudioSessionProperty_OverrideCategoryMixWithOthers,
sizeof (doSetProperty),
&doSetProperty
);
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
And remove the AudioSessionSetProperty, or change doSetProperty to 1.
No need to subclass Window or forward events. Simply handle it from your main view controller. See the Audio Mixer (MixerHost) example for details.
http://developer.apple.com/LIBRARY/IOS/#samplecode/MixerHost/Listings/Classes_MixerHostViewController_m.html
Documentation explains it very well.
https://developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/Remote-ControlEvents/Remote-ControlEvents.html
One thing that seems to influence this behavior is any category options you set for your AVAudioSession using setCategory:withOptions:error: instead of just setCategory:error:. In particular, from trial and error, it appears that if you set AVAudioSessionCategoryOptionMixWithOthers you will not get remote control events; the now playing controls will still control the iPod app. If you set AVAudioSessionCategoryOptionDuckOthers you will get remote control events, but it seems like there may be some ambiguity regarding which app is controlled. Setting the categoryOptions to 0 or just calling setCategory:error: works best.

iPad rotation bug when using MPMoviePlayerViewController

Issue summary
Changing the orientation of an iPad device or simulator while playing a video using MPMoviePlayerViewController results in an inconsistent rotation state upon dismissal of the video player. This is a known bug in iPad SDK 3.2, documented at http://www.openradar.me/8012810
Sample project
I have prepared a minimal sample project using the View-based Application template from Xcode 3.2.2, using the following code to launch the player
NSURL *movieUrl = [NSURL URLWithString:#"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"];
MPMoviePlayerViewController *player = [[MPMoviePlayerViewController alloc] initWithContentURL:movieUrl];
[self presentMoviePlayerViewControllerAnimated:player];
[player release];
The code is available on GitHub at http://github.com/adamalex/FullScreenMovie or direct download using http://github.com/adamalex/FullScreenMovie/zipball/master
Steps to reproduce
Obtain the project using the information above
Launch the project with the iPad simulator or device
Tap the button to begin playing the video
Rotate the iPad by 90 degrees
Dismiss the video
Note the UIStatusBar is out of sync with the application UI
Objective
I have contacted Apple and they have confirmed this is a bug that is being investigated. I would like to discuss temporary workarounds that use public APIs safe for submission to the App Store. I am going to open a developer support case with Apple as well and will report back with my own progress.
Successful response from Apple Developer Technical Support!
This is a known bug and a we're received a number of duplicate bug reports and so iOS engineering is aware of the issue and we do have a temporary workaround as suggested by iOS engineering.
You will need to implement this in the view controller which presents the movie player.
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
[self performSelector:#selector(fixStatusBar) withObject:nil afterDelay:0];
}
- (void)fixStatusBar {
[[UIApplication sharedApplication] setStatusBarOrientation:[self interfaceOrientation] animated:NO];
}
While this is somewhat ugly, it should fix the issue for now. It would be recommended to remove this code once the bug is fixed in the system.
This took care of the issue completely for me, and you can revisit http://github.com/adamalex/FullScreenMovie for the code with the fix applied.
This also solves an iPhone/iPodTouch rotation issue that I was struggling with. I am developing a universal app in which each view displays a different image depending on whether the device is in portrait or landscape orientation. Buttons are used to navigate between views.
If the app is running on the device and a portrait view is rotated to landscape, my image switching takes place. If the device is then placed flat on a table top and the button is tapped to display the next view, the view appears in landscape but shows the portrait image instead. I solved the problem by forcing a portrait view to appear by detecting for face up and down, but Apple's code solved this problem (as well as the similar movie problem I was also experiencing).
Many thanks for reporting the bug - I assumed it was just my bad coding...