iphone - play audio stream in background - iphone

I'm using xcode 4.2 and building an iphone app, and have a view that when opened plays an audio stream.
What i try to achieve is have the app continue playing even if it enters the background.
I've tried any possible solution that i found in stackoverflow or elsewhere (and there are many available), but can't get it work. When the application enters background the audio stops, when i open the app again the audio continues.
In my Info.plist ia have set 2 rows:
Required Background Modes -> App plays audio &
Application does not run in background -> NO
What am i missing? what else is needed to keep playing the audio in the background?
Thank you in advance.
EDIT:
I see many answers on the issue, suggestiong the use of AVAudio Framework. Is there any chance that MPMoviePlayerController is not able to play the stream in the background? Should i change to AVAudio?
EDIT 2:
Ok, seems it's too complex for me to achieve. I'm giving the exact code, hope this will help.
RadioStreamer.h
#import <UIKit/UIKit.h>
#import "MediaPlayer/MediaPlayer.h"
#interface RadioStreamer : UIViewController {
MPMoviePlayerController *player;
IBOutlet UIButton *playButton;
IBOutlet UIButton *pauseButton;
}
#property (nonatomic, retain) MPMoviePlayerController *player;
#property (nonatomic, retain) IBOutlet UIButton *playButton;
#property (nonatomic, retain) IBOutlet UIButton *pauseButton;
- (IBAction)playButtonPressed:(id)button;
- (IBAction)pauseButtonPressed:(id)button;
- (void) playAudio;
- (void) pauseAudio;
#end
RadioStreamer.m
#import "RadioStreamer.h"
#import "tabbartestAppDelegate.h"
#implementation RadioStreamer
#synthesize player;
#synthesize playButton;
#synthesize pauseButton;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
return self;
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title=#"";
// Do any additional setup after loading the view from its nib.
if (!self.player) {
player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:#"http://s6.onweb.gr:8006/listen.pls"]];
player.movieSourceType = MPMovieSourceTypeStreaming;
player.view.frame = CGRectMake(55, 180, 200, 30);
player.backgroundView.backgroundColor = [UIColor clearColor];
player.view.backgroundColor = [UIColor clearColor];
[self.view addSubview:player.view];
[player play];
}
}
- (void) playAudio {
if (player.playbackState != MPMoviePlaybackStatePlaying){
[player play];
}
}
- (void) pauseAudio {
if (player.playbackState == MPMoviePlaybackStatePlaying) {
[player pause];
}
}
- (IBAction)playButtonPressed:(id)button {
[self playAudio];
}
- (IBAction)pauseButtonPressed:(id)button {
[self pauseAudio];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)dealloc {
[self.player release];
[self.playButton release];
[self.pauseButton release];
self.player = nil;
self.playButton = nil;
self.pauseButton = nil;
}
#end

Check your audio session setup as that might need some extra attention.
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
error:nil];
[[AVAudioSession sharedInstance] setActive:YES
error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

How stumbled upon the programming tutorial in details at this place.
http://mobisoftinfotech.com/integrate-music-player-in-iphone/
This should play the music within the app and also continue to play if you take your app in background.

Related

How to display the video captured from iPhone's camera on the screen without saving it?

I am new to iOS and multimedia development and I am trying to capture a video from iPhone's camera and show it on the screen without saving it in the memory.
I have written the following code so far with the help of sample codes that I got online:
Header file:
// ViewController.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#class AVCamCaptureManager, AVCamPreviewView, AVCaptureVideoPreviewLayer;
#interface ViewController : UIViewController <UIImagePickerControllerDelegate>
#property (weak, nonatomic) IBOutlet UIView *previewView;
- (IBAction)StartCapture:(id)sender;
- (void)setCaptureSession;
#end
Implementation file
// ViewController.m
#import "ViewController.h"
#interface ViewController ()
#property (nonatomic, strong) AVCaptureSession *captureSession;
#property (nonatomic, strong) AVCaptureMovieFileOutput *captureOutput;
#property (nonatomic, weak) AVCaptureDeviceInput *activeVideoInput;
#property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)StartCapture:(id)sender
{
if ([sender isSelected])
{
[sender setSelected:NO];
[self.captureOutput stopRecording];
}
else
{
[sender setSelected:YES];
if (!self.captureOutput)
{
self.captureOutput = [[AVCaptureMovieFileOutput alloc] init];
[self.captureSession addOutput:self.captureOutput];
}
[self.captureSession startRunning];
}
}
- (void)setCaptureSession
{
self.captureSession = [[AVCaptureSession alloc] init];
NSError *error;
// Set up hardware devices
AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if (videoDevice)
{
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
if (input)
{
[self.captureSession addInput:input];
self.activeVideoInput = input;
}
}
AVCaptureDevice *audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
if (audioDevice) {
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&error];
if (audioInput) {
[self.captureSession addInput:audioInput];
}
}
// Start running session so preview is available
[self.captureSession startRunning];
// Set up preview layer
dispatch_async(dispatch_get_main_queue(), ^{
self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
self.previewLayer.frame = self.previewView.bounds;
self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
//[[self.previewLayer connection] setVideoOrientation:[self currentVideoOrientation]];
[self.previewView.layer addSublayer:self.previewLayer];
});
}
// Re-enable capture session if not running currently
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if (![self.captureSession isRunning])
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self.captureSession startRunning];
});
}
}
// Stop running capture session when this view disappears
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
if ([self.captureSession isRunning])
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self.captureSession stopRunning];
});
}
}
#end
Please tell me what should I write in the IBAction method (which gets called when capture video button is pressed) and how to use AVCaptureVideoPreviewLayer to make the video being captured to be displayed on the screen.
Thanks.
I found what I was missing. It was really stupid for me to do this. I didn't call the function setCapture at all. Hence nothing was getting visible on the screen.
I just called setCapture in viewDidLoad function and problem solved.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self setCaptureSession];
}
Still there is an issue with the video when phone's orientation is changed which I will have to work upon but now whatever is being captured by the camera is visible on the screen.
You want an AVCapturePreviewLayer.
https://developer.apple.com/library/ios/documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/04_MediaCapture.html#//apple_ref/doc/uid/TP40010188-CH5-SW22
As far as what to write in your IBAction method, that'll depend on how you want your app to behave. If you want it to load with the capture session and preview running, you don't really need a button. If you're starting your capture session via the button, just put the PreviewLayer code in the same method (after you have inited your capture session).

OpenCV video processing tutorial issue

I followed the iOS video processing tutorial on the OpenCV site and managed to compile and install it on the device. However when I click on the "Start" button, nothing visible happens. Apparently neither my - (void)processImage:(Mat&)image callback is never called. Could you give me some hints what could be the problem?
Some things I checked:
actionStart is called, and both log lines prints YES
the self object is valid when assigned to self.videoCamera.delegate
imageView is valid and visible on the screen
videoCamera is initialized when its start method is called
I use a iPhone 3GS for testing.
Here is the full source of my ViewController.h:
#import <UIKit/UIKit.h>
#import <opencv2/highgui/cap_ios.h>
#interface ViewController : UIViewController <CvVideoCameraDelegate>
{
IBOutlet UIImageView* imageView;
IBOutlet UIButton* button;
CvVideoCamera* videoCamera;
}
- (IBAction)actionStart:(id)sender;
#property (nonatomic, strong) CvVideoCamera* videoCamera;
#end
and ViewController.mm:
#implementation ViewController
#synthesize videoCamera;
- (void)viewDidLoad
{
[super viewDidLoad];
self.videoCamera = [[CvVideoCamera alloc] initWithParentView:imageView];
self.videoCamera.delegate = self;
self.videoCamera.defaultAVCaptureDevicePosition = AVCaptureDevicePositionFront;
self.videoCamera.defaultAVCaptureSessionPreset = AVCaptureSessionPreset352x288;
self.videoCamera.defaultAVCaptureVideoOrientation = AVCaptureVideoOrientationPortrait;
self.videoCamera.defaultFPS = 30;
self.videoCamera.grayscaleMode = NO;
}
#pragma mark - UI Actions
- (IBAction)actionStart:(id)sender;
{
[self.videoCamera start];
NSLog(#"video camera running: %d", [self.videoCamera running]);
NSLog(#"capture session loaded: %d", [self.videoCamera captureSessionLoaded]);
}
#pragma mark - Protocol CvVideoCameraDelegate
- (void)processImage:(cv::Mat&)image
{
// Do some OpenCV stuff with the image
cv::Mat image_copy;
cvtColor(image, image_copy, CV_BGRA2BGR);
// invert image
bitwise_not(image_copy, image_copy);
cvtColor(image_copy, image, CV_BGR2BGRA);
}
#end
I tested on an iPhone 4 and it works well. Maybe the iPhone 3GS doesn't have a front facing camera? Then you have to change this line: self.videoCamera.defaultAVCaptureDevicePosition = AVCaptureDevicePositionFront to self.videoCamera.defaultAVCaptureDevicePosition = AVCaptureDevicePositionBack

UIWebView is not loading url

I know this is a common question but none of the answers fix my problem. I have a UIWebView in my app. I have everything set up correctly; the delegate is set, the webView is a property of my view controller. It is set up to load an html string upon loading the viewController. When the html string loads, in the webViewDidFinishLoad method it checks if this is the first time it loaded, and if it is it is told to load a request with a url. The string i use for the url is a property of my viewController. That string is exactly what it is supposed to be. There is just something preventing the webView from actually loading the request. Any ideas would be very much appreciated. Thank you
#interface WebViewController : UIViewController <UIWebViewDelegate, UIActionSheetDelegate, UIPrintInteractionControllerDelegate, MFMailComposeViewControllerDelegate, NSURLConnectionDelegate>
#property (nonatomic, assign) BOOL firstLoad;
#property (nonatomic, retain) UIWebView *webView;
#property (nonatomic, retain) NSString *prefixURLString;
#property (nonatomic, retain) NSString *suffixURLString;
#property (nonatomic, retain) UIActionSheet *actionSheet;
- (id)initWithTitle:(NSString *)newTitle andSuffixURL:(NSString *)suffix;
- (void)reload;
- (void)addActionButton;
- (void)showActions:(UIBarButtonItem *)sender;
- (void)dismissActionSheet;
#end
#implementation WebViewController
#synthesize webView;
#synthesize prefixURLString;
#synthesize suffixURLString;
#synthesize firstLoad;
#synthesize actionSheet;
- (id)initWithTitle:(NSString *)newTitle withPrefixURL:(NSString *)prefix andSuffixURL:(NSString *)suffix
{
self = [super initWithNibName:nil bundle:nil];
if (self) {
// Custom initialization
[self setPrefixURLString:prefix];
[self setFirstLoad:YES];
[self setTitle:newTitle];
[self setSuffixURLString:suffix];
[self setActionSheet:nil];
}
return self;
}
- (id)initWithTitle:(NSString *)newTitle andSuffixURL:(NSString *)suffix
{
return [self initWithTitle:newTitle withPrefixURL:#"https://customer.stld.com/flatroll/ios/%#" andSuffixURL:suffix];
}
- (void)reload
{
if(self.prefixURLString && self.suffixURLString)
{
NSString *fullURLString = [NSString stringWithFormat:self.prefixURLString, [self.suffixURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:fullURLString]]];
}
}
- (void)dealloc
{
[suffixURLString release]; suffixURLString = nil;
[prefixURLString release]; prefixURLString = nil;
[actionSheet release]; actionSheet = nil;
[super dealloc];
}
- (void):(UIWebView *)aWebView didFailLoadWithError:(NSError *)error
{
//NSLog(#"WebViewController:DidFailLoadWithError: %#", [error localizedFailureReason]);
[self setTitle:#"Loading Error"];
[self.webView loadHTMLString:[NSString stringWithFormat:#"<html><head><meta name=\"viewport\" content=\"width=device-width, user-scalable=yes\" /></head><body>Loading error:<br />%#</body></html>", [error localizedFailureReason]] baseURL:nil];
}
- (void)webViewDidFinishLoad:(UIWebView *)aWebView
{
if(self.firstLoad)
{
[self setFirstLoad:NO];
[self reload];
[self addActionButton];
}
}
#pragma mark - View lifecycle
- (void)loadView
{
UIWebView *newWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
[newWebView setDelegate:self];
[newWebView setScalesPageToFit:YES];
[newWebView setUserInteractionEnabled:YES];
[self setWebView:newWebView];
[self setView:newWebView];
[newWebView release];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self.webView loadHTMLString:#"<html><head><meta name=\"viewport\" content=\"width=device-width, user-scalable=yes\" /></head><body><br />Gathering data and generating report.<br />Depends on data and parameters you have requested, this could take time. Please wait...</body></html>" baseURL:nil];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
[self.webView setDelegate:nil];
[self setWebView:nil];
[self setView:nil];
}
I had the same problem, I'm not entirely sure why, but I guess it has to do something with viewControllers life cycle. Anyway try load URL in viewDidAppear method. It fixed it for me. Hope it will help
It turns out my problem had nothing to do with the UIWebView. I just had to change the credential persistence in the URLConnectionDelegate I had set up for my app. I had it set as NSURLCredentialPersistanceNone but I changed it to NSURLCredentialPersistenceSession. I hope this can help anyone else out there who had the exact problem as I did

Adding a NSTimer to a button

I have searched all over the web with no luck of making this project work with a timer, I end up with a crashed app every time when using the timer.
For testing and learning purposes I build little simple apps. It is a button that sends a rocket from the bottom of the screen and disappears off screen, along with a rocket sound effect.
I am wanting to add a Timer to the button so that when the button is held down the rocket will launch, reset, and launch over and over until I release the button. I think my only hope now is to paste code from my .h & .m files and hopefully someone can tell me what I need to do and where the proper code needs to be added for this project.
Thank you so much for the help, it is greatly appreciated.
.H FILE:
// MVViewController.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#interface MVViewController : UIViewController
#property (strong, nonatomic) IBOutlet UIImageView *moveMe2;
//New action to repeat launch (Touch Down)
- (IBAction)rocketRepeat:(id)sender;
//New action to stop launch (Touch Up Inside)
- (IBAction)rocketStop:(id)sender;
//This is the original launch button (Touch Down)
- (IBAction)yourRocketButton:(id)sender;
#end
.M FILE
// MVViewController.m
#import "MVViewController.h"
#interface MVViewController ()
#end
#implementation MVViewController {
AVAudioPlayer *audioPlayer;
}
#synthesize moveMe2;
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[self setMoveMe2:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return ((interfaceOrientation == UIInterfaceOrientationPortrait) || (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown));
}
- (IBAction)rocketRepeat:(id)sender
//Getting error "Use of undeclared identifier 'yourRocketButton'
{
[yourRocketButton addTarget:self action:#selector(rocketRepeat:) forControlEvents:UIControlEventTouchDown];
}
- (IBAction)rocketStop:(id)sender
//Getting error "Use of undeclared identifier 'yourRocketButton'
{
[yourRocketButton addTarget:self action:#selector(rocketStop:) forControlEvents:UIControlEventTouchUpInside];
}
- (IBAction)yourRocketButton:(id)sender {
moveMe2.center = CGPointMake(100.0f, 408.0f);
[UIView animateWithDuration:2.0 animations:^{moveMe2.center = CGPointMake(100, -55);}];
}
#end
########
EDIT *This is what finally worked*
// RKViewController.m
#import "RKViewController.h"
#interface RKViewController ()
#end
#implementation RKViewController
#synthesize RocketMove;
#synthesize Launch;
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewDidUnload
{
[self setRocketMove:nil];
[self setLaunch:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return ((interfaceOrientation == UIInterfaceOrientationPortrait) || (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown));
}
- (IBAction)rocketRepeat:(id)sender {
[self performSelector:#selector(rocketRepeat:) withObject:self afterDelay:1.0];
RocketMove.center = CGPointMake(100.0f, 408.0f);
[UIView animateWithDuration:1.0 animations:^{RocketMove.center = CGPointMake(100, -55);}];
}
- (IBAction)rocketStop:(id)sender {
[NSObject cancelPreviousPerformRequestsWithTarget:self];
}
#end
// RKViewController.h
#import <UIKit/UIKit.h>
#interface RKViewController : UIViewController
#property (strong, nonatomic) IBOutlet UIImageView *RocketMove;
#property (strong, nonatomic) IBOutlet UIButton *Launch;
- (IBAction)rocketRepeat:(id)sender;
- (IBAction)rocketStop:(id)sender;
#end
You have to use UIControlEvent for this purpose.
1. You need two separate IBActions for each purpose, say one for holding down the button, one after the button is released.
2. For holding down the button you need to use UIControlEventTouchDown. So have a rocketRepeat action where you keep calling the rocket action using the NSTimer with regular intervals and use:
[yourRocketButton addTarget:self action:#selector(rocketRepeat:) forControlEvents:UIControlEventTouchDown];
3. Then use another action with UIControlEventTouchUpInside where you will invalidate the NSTimer so the rocket stops. Call that action rocketStop or something and use:
[yourRocketButton addTarget:self action:#selector(rocketStop:) forControlEvents:UIControlEventTouchUpInside];
---EDIT---
Action 1 :
- (IBAction)rocketRepeat:(id)sender
{
//code for starting rocker, timer action
}
Action 2:
- (IBAction)rocketStop:(id)sender
{
//Code for stopping rocket
}
yourButton is not an action, its a UIButton. I hope you have created a button in the IB, drag and dropped the button. And in viewDidLoad you write these 2 lines of code :
Instead of yourButton you write the name of the button you have dragged dropped from the IB. I hope you know how to add a button from the interface builder and connect it.
- (void)viewDidLoad
{
[yourRocketButton addTarget:self action:#selector(rocketRepeat:) forControlEvents:UIControlEventTouchDown]; //For touch down button action
[yourRocketButton addTarget:self action:#selector(rocketStop:) forControlEvents:UIControlEventTouchUpInside]; //When button is let go.
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
If you want that the rockets are autolaunched once you press the button, you should add the following code to your rocketLaunch: method. If you want them to start appearing from the beginning, call this from your viewDidLoad method.
- (void)launchRocketsTimer
{
[self.timer invalidate]; //you have to create a NSTimer property to your view controller
self.timer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:#selector(scheduledRocketLaunch:) userInfo:nil repeats:YES];
}
- (void)scheduledRocketLaunch:(NSTimer *)t
{
moveme2.center = _bottom_point_; //set it where you would like it to start
[UIView animateWithDuration:2.0 animations:^{moveMe2.center = CGPointMake(100, -55);}];
}
Remember to release your timer in dealloc.
Oh, and one more thing:
You have a memory leak on your rocketsound: method when you allocate your AVAudioPlayer. You may replace the code with this one:
- (IBAction)rocketsound:(id)sender
{
NSURL *url = [NSURL fileURLWithPath: [NSString stringWithFormat:#"%#/rocketlaunch.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
if (self.audioPlayer == nil)
{
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error] autorelease]; //Note the use of setter property and the autorelease. (you could use your own code because the if will prevent the leak in this case).
}
audioPlayer.numberOfLoops = 0;
if (audioPlayer == nil)
NSLog(#"%#", [error description]);
else
[audioPlayer play];
}

iPhone iOS4 low-level camera control?

Is there a way to manually set low-level still-camera settings like shutter speed, aperture, or ISO in iOS4 on the iPhone 4? I don't think it exists in the official SDK but perhaps someone has found some private APIs to allow this?
I find my iPhone 4 camera to be unusable because even in fairly decent lighting, it always insists on shooting at the slowest 1/15th a second shutter speed causing motion blur if the subject is moving at all.
Thanks!
Not directly. Please file a bug report.
Yes, there may be private APIs available, but that's of limited use.
Try this, I could be useful for you:
#interface MyViewController ()
#property (nonatomic, retain) IBOutlet UIImageView *imageView;
#property (nonatomic, retain) IBOutlet UIToolbar *myToolbar;
#property (nonatomic, retain) OverlayViewController *overlayViewController;
#property (nonatomic, retain) NSMutableArray *capturedImages;
// toolbar buttons
- (IBAction)photoLibraryAction:(id)sender;
- (IBAction)cameraAction:(id)sender;
#end
#implementation MyViewController
- (void)viewDidLoad
{
self.overlayViewController =
[[[OverlayViewController alloc] initWithNibName:#"OverlayViewController" bundle:nil] autorelease];
// as a delegate we will be notified when pictures are taken and when to dismiss the image picker
self.overlayViewController.delegate = self;
self.capturedImages = [NSMutableArray array];
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
// camera is not on this device, don't show the camera button
NSMutableArray *toolbarItems = [NSMutableArray arrayWithCapacity:self.myToolbar.items.count];
[toolbarItems addObjectsFromArray:self.myToolbar.items];
[toolbarItems removeObjectAtIndex:2];
[self.myToolbar setItems:toolbarItems animated:NO];
}
}
- (void)viewDidUnload
{
self.imageView = nil;
self.myToolbar = nil;
self.overlayViewController = nil;
self.capturedImages = nil;
}
- (void)dealloc
{
[_imageView release];
[_myToolbar release];
[_overlayViewController release];
[_capturedImages release];
[super dealloc];
}
- (void)showImagePicker:(UIImagePickerControllerSourceType)sourceType
{
if (self.imageView.isAnimating)
[self.imageView stopAnimating];
if (self.capturedImages.count > 0)
[self.capturedImages removeAllObjects];
if ([UIImagePickerController isSourceTypeAvailable:sourceType])
{
[self.overlayViewController setupImagePicker:sourceType];
[self presentModalViewController:self.overlayViewController.imagePickerController animated:YES];
}
}
- (IBAction)photoLibraryAction:(id)sender
{
[self showImagePicker:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (IBAction)cameraAction:(id)sender
{
[self showImagePicker:UIImagePickerControllerSourceTypeCamera];
}
// as a delegate we are being told a picture was taken
- (void)didTakePicture:(UIImage *)picture
{
[self.capturedImages addObject:picture];
}
// as a delegate we are told to finished with the camera
- (void)didFinishWithCamera
{
[self dismissModalViewControllerAnimated:YES];
if ([self.capturedImages count] > 0)
{
if ([self.capturedImages count] == 1)
{
// we took a single shot
[self.imageView setImage:[self.capturedImages objectAtIndex:0]];
}
else
{
// we took multiple shots, use the list of images for animation
self.imageView.animationImages = self.capturedImages;
if (self.capturedImages.count > 0)
// we are done with the image list until next time
[self.capturedImages removeAllObjects];
self.imageView.animationDuration = 5.0; // show each captured photo for 5 seconds
self.imageView.animationRepeatCount = 0; // animate forever (show all photos)
[self.imageView startAnimating];
}
}
}
#end