App crashes with unrecognized selector sent to instance - ios

This is the error Xcode shoy my:
2013-10-25 11:43:35.059 ChineseCheckers[7220:c07] -[HomeViewController
play:]: unrecognized selector sent to instance 0x8a2de20 2013-10-25
11:43:35.062 ChineseCheckers[7220:c07] * Terminating app due to
uncaught exception 'NSInvalidArgumentException', reason:
'-[HomeViewController play:]: unrecognized selector sent to instance
0x8a2de20'
* First throw call stack:
(0x1af7012 0x14a4e7e 0x1b824bd 0x1ae6bbc 0x1ae694e 0xeed2c0 0x1ab6376
0x1ab5e06 0x1a9da82 0x1a9cf44 0x1a9ce1b 0x278b7e3 0x278b668 0x3e8ffc
0x28fd 0x2def725 0x1) libc++abi.dylib: terminate called throwing an
exception (lldb) 0x8a2de20
I`m traying to put a background sound to my app , I put the sourece code
-(IBAction)play
{
NSString *soundFilePath =[[NSBundle mainBundle] pathForResource: #"larga"ofType: #"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
AVAudioPlayer *newPlayer =[[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: Nil];
self.player = newPlayer;
[self.player prepareToPlay];
[self.player setDelegate: self];
[self.player play];
[NSTimer scheduledTimerWithTimeInterval: 30 target: self
selector: #selector(play:) userInfo: nil repeats: YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
.............................
...............................
[self.player play];
}

With this:
[NSTimer scheduledTimerWithTimeInterval: 30 target: self
selector: #selector(play:) userInfo: nil repeats: YES];
You are calling the method play on your view controller, at that method doesn't exist.
Try creating it (remove the : from play: in the selector):
[NSTimer scheduledTimerWithTimeInterval: 30 target: self
selector: #selector(play) userInfo: nil repeats: YES];
-(void)play
{
[self.player play];
}

Related

How to stop audio in background mode?

I want to stop audio in background mode in first controller and play audio in background mode in second controller.
I use this code:
NSString *soundFilePath = [NSString stringWithFormat:#"%#/%#.mp3",[[NSBundle mainBundle] resourcePath], #"sound"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
_player.numberOfLoops = 1000;
[_player play];
To stop audio in background mode I use this code:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error: nil];
[[AVAudioSession sharedInstance] setActive: NO error: nil];
To play audio in background mode I use this code:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error: nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
But my code to stop audio doesn't work...
UPD
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[NSNotificationCenter.defaultCenter addObserver:self selector:#selector(handleForgroundScenario) name:UIApplicationWillEnterForegroundNotification object:nil];
[NSNotificationCenter.defaultCenter addObserver:self selector:#selector(handleBackgroundScenario) name:UIApplicationWillResignActiveNotification object:nil];
}
-(void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[NSNotificationCenter.defaultCenter removeObserver:self];
}
-(void) handleForgroundScenario {
if([self.player rate] == 0) {
[_player play];
}
}
-(void) handleBackgroundScenario {
[_player pause];
}
- (void)viewDidLoad
{
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
[[AVAudioSession sharedInstance]
setCategory: AVAudioSessionCategoryPlayback
error: nil];
[super viewDidLoad];
NSString *soundFilePath = [NSString stringWithFormat:#"%#/%#.mp3",[[NSBundle mainBundle] resourcePath], #"sound"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
_player.numberOfLoops = 1000;
[_player play];
}
Add ApplicationWillResign notification in ViewWillAppear of ViewController in which you wanna pause player
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(handleBackgroundScenario), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
}
Pause player in selector
#objc func handleBackgroundScenario() {
//pause
}
Finally remove observer in viewWillDisappear
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self)
}
This will make sure that notification will be triggered only when ViewController is loaded and app goes to background.
For all other VC notification will not trigger the selector and hence it will not alter the behavior of player
EDIT:
Code in Objective - C
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[NSNotificationCenter.defaultCenter addObserver:self selector:#selector(handleBackgroundScenario) name:UIApplicationWillResignActiveNotification object:nil];
}
-(void) handleBackgroundScenario {
//pause player
[_player pause];
}
-(void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[NSNotificationCenter.defaultCenter removeObserver:self];
}
EDIT:
Where I should call player after app become alive?
By the statement u mean when to start player when app comes to foreground you can use
[NSNotificationCenter.defaultCenter addObserver:self selector:#selector(handleForgroundScenario) name:UIApplicationDidBecomeActiveNotification object:nil];
Finally implement handleForgroundScenario
-(void) handleForgroundScenario {
if([self.player rate] == 0) {
[_player play];
}
}

Instance of class AVPlayer was deallocated

I have a UIView that responds to a single tap gesture by playing an audio file. It does this by using the AVPlayer class. It all works well with one exception. If a user is currently listening to an audio file, and they tap the same UIView again, I want the audio file to return to the beginning and start playing again from the start. However, when this occurs, I get the following console output:
An instance 0x10ad89dd0 of class AVPlayer was deallocated while key
value observers were still registered with it. Observation info was
leaked, and may even become mistakenly attached to some other object.
The first three lines in my play method are my attempt to deal with this, but they don't solve anything. The audio does restart, but the controls (time played, sliders, etc) all go crazy. I see a couple of other posts on this, I'm still stuck. Can anyone see what I need to do to clear this problem?
- (void) playAudio : (UITapGestureRecognizer *)recognizer
{
// remove any existing observers to prevent memory leaks
[self.audioPlayer pause];
self.audioPlayer = nil;
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.audioPlayer];
unsigned long buttonPressed = [self.buttonsArray indexOfObject:recognizer.view];
Sessions *session = self.sessionsList[buttonPressed];
self.mediaFile = session.media_file;
self.totalSecondsToPlay = [session.play_seconds integerValue];
[self resetAVControls];
NSString *urlString = [NSString stringWithFormat:#"%#%#", AUDIO_URL, self.mediaFile];
AVPlayer *player = [[AVPlayer alloc]initWithURL:[NSURL URLWithString:urlString]];
self.audioPlayer = player;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:[self.audioPlayer currentItem]];
[self.audioPlayer addObserver:self forKeyPath:#"status" options:0 context:nil];
self.isPlaying = YES;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(updateProgress)
userInfo:nil
repeats:YES];
}
You've registered KeyValueObservers for self.audioPlayer, but you haven't removed them when you are setting the value to nil. So before doing self.audioPlayer = nil; unsubscribe to KVO by using [self.audioPlayer removeObserver:self forKeyPath:#"status" context:nil]
Check this if you want to know more about KVO
Each time when your set your playerview to nil, before call removeObserver.
Example
[self removeObserverForStatusPlay];
playerView = nil;
And before Init
[self removeObserverForStatusPlay];
playerView = [[AVPlayer alloc] initWithURL:url];
When removeObserverForStatusPlay method is
- (void)removeObserverForStatusPlay
{
#try {
[playerView removeObserver:self forKeyPath:#"status"];
} #catch(id anException) {
NSLog(#"excepcion remove observer == %#. Remove previously or never added observer.",anException);
//do nothing, obviously it wasn't attached because an exception was thrown
}
}

Movie play error - nil string

I am trying to play a movie in ios but i keep getting error.
My code:
-(IBAction)playMovie:(id)sender
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"big-buck-bunny-clip" ofType:#"m4v"];
NSURL *fileURL = [NSURL fileURLWithPath:filepath];
MPMoviePlayerController *moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlaybackComplete:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:moviePlayerController];
[self.view addSubview:moviePlayerController.view];
moviePlayerController.fullscreen = YES;
[moviePlayerController play];
}
- (void)moviePlaybackComplete:(NSNotification *)notification
MPMoviePlayerController *moviePlayerController = [notification object];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:moviePlayerController];
[moviePlayerController.view removeFromSuperview];
[moviePlayerController.view setFrame:CGRectMake(38, 100, 250, 163)];
[self.view addSubview:moviePlayerController.view];
//moviePlayerController.fullscreen = YES;
[moviePlayerController play];
}
the error is:
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '*** -[NSURL
initFileURLWithPath:]: nil string parameter'
ok i got it .. i forgot to add the file in build phase ...

*** Terminating app due to uncaught exception 'NSInvalidArgumentException',

i am newbie to iOS and i want to implement a splash screen and load the data from database then transmit to another view controller to display data in a UITableView
here is my code
#import "SplashViewController.h"
#import "DataLoader.h"
#import "UISessionTable.h"
#interface SplashViewController ()
#end
#implementation SplashViewController
#synthesize sessionsDataFromDatabase;
-(void) viewDidLoad{
[super viewDidLoad];
double currentTime = [[NSDate date] timeIntervalSince1970];
dispatch_queue_t downloadQueue = dispatch_queue_create("session data loader", NULL);
dispatch_async(downloadQueue, ^{
//code to load session into array
self.sessionsDataFromDatabase = [DataLoader getSessions];
dispatch_async(dispatch_get_main_queue(), ^{
double differance = 5000.0 - ([[NSDate date] timeIntervalSince1970] - currentTime) ;
differance = differance<0? 0:differance;
[[NSTimer scheduledTimerWithTimeInterval: differance target:self
selector: #selector(pushToSessionTableViewController:) userInfo: nil repeats: NO]fire];
});
});
dispatch_release(downloadQueue);
}
-(void) viewDidUnload{
[super viewDidUnload];
self.sessionsDataFromDatabase = nil;
}
-(void) pushToSessionTableViewController{
UISessionTable * obj = [[UISessionTable alloc]init ];
[obj setSessionsData:self.sessionsDataFromDatabase];
[self.navigationController pushViewController:obj animated:YES];
}
#end
i got the following error when run
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason:
'-[SplashViewController pushToSessionTableViewController:]: unrecognized selector sent
to instance 0x6e45740'
any suggestion ???
The colon at the end is for methods that receive parameters, yours doesn't receive anything. That's why it can't find the method (it assumes it is another undeclared method).
Replace
pushToSessionTableViewController:
with
pushToSessionTableViewController

iOS streaming video error

I get following error:
2012-04-04 23:46:18.374 istiqlaltv[17121:e903] -[istiqlaltvViewController moviePlayBackDidFinish]: unrecognized selector sent to instance 0x6136ee0
2012-04-04 23:46:18.380 istiqlaltv[17121:e903] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[istiqlaltvViewController moviePlayBackDidFinish]: unrecognized selector sent to instance 0x6136ee0'
This is code, I am very new in iOS, I just want to play a streaming video when you press the play button.
-(void)playVideo{
NSURL *url = [[NSURL alloc] initFileURLWithPath:#"http://blabla.com/playlist.m3u8"];
NSString *strVersion = [[UIDevice currentDevice] systemVersion];
float version = [strVersion floatValue];
if(version < 4.0){
MPMoviePlayerController *themovie = [[MPMoviePlayerController alloc] initWithContentURL:url];
themovie.scalingMode = MPMovieScalingModeAspectFill;
[themovie play];
}else{
MPMoviePlayerViewController *themovie = [[MPMoviePlayerViewController alloc]initWithContentURL:url];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(moviePlayBackDidFinish) name:MPMoviePlayerPlaybackDidFinishNotification object:themovie.moviePlayer];
[self presentMoviePlayerViewControllerAnimated:themovie];
}
}
-(void) moviePlayBackDidFinish:(NSNotification *)notification{
MPMoviePlayerController *player = [notification object];
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:player];
[player stop];
[self dismissMoviePlayerViewControllerAnimated];
}
Any help?
You are missing the : in the moviePayBlackDidFinish: selector when you add your observer:
Should be:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(moviePlayBackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:themovie.moviePlayer];
Note that the colon after the method name indicates that the method takes a parameter. You were getting the error because your code was looking for a method named moviePlaybackDidFinish that does not take a parameter, but no such method exists.

Resources