I need to programmatically click a button: [play sendActionsForControlEvents:UIControlEventTouchUpInside];
But when I do that the void was called twice! I need to start a AVPlayer (in ViewDidLoad), but the music started twice too. Please help :).
The play code:
- (IBAction)playStream:(id)sender {
NSLog(#"%#", #"PlayStream clicked: ", sender);
if(clicked == 0) {
clicked = 1;
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
[play setImage:[UIImage imageNamed:#"pause"] forState:UIControlStateNormal];
[playerr play];
}
else {
[playerr stop];
[play setImage:[UIImage imageNamed:#"Start"] forState:UIControlStateNormal];
[audio setActive:NO error:nil];
clicked = 0;
}
}
How about:
#implementation MyClassName{
BOOL musicPlaying;
}
- (IBAction)playStream:(id)sender {
if(musicPlaying){
[self pauseMusic];
}else{
[self playMusic];
}
}
-(void)playMusic{
musicPlaying= YES;
[play setImage:[UIImage imageNamed:#"pause"] forState:UIControlStateNormal];
[playerr play];
}
-(void)pauseMusic{
musicPlaying= NO;
[playerr stop];
[play setImage:[UIImage imageNamed:#"Start"] forState:UIControlStateNormal];
[audio setActive:NO error:nil];
}
Now instead of tapping the button programmatically, just call playMusic or pauseMusic.
Related
I have just successfully set up somewhat of a music player. It queries the user's iTunes and plays songs based on the query. For some reason, the button, won't change when the Playback state changes. I have both and NSLog and Label and they both reference it but when it comes to the button, nothing happens. Here's the code:
- (void) handle_PlaybackStateChanged: (id) notification {
MPMusicPlaybackState playbackState = [self.player playbackState];
if (playbackState == MPMusicPlaybackStatePaused) {
self.textLabel.text = #"play";
[PlayButton setTitle:#"STOP" forState:UIControlStateNormal]; // To set the title
NSLog (#"This is paused");
self.playBarButton.title = #"Play";
self.PlayButton = PlayButton;
[self.PlayButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
} else if (playbackState == MPMusicPlaybackStatePlaying) {
self.textLabel.text = #"pause";
[PlayButton setTitle:#"Pause" forState:UIControlStateNormal];
self.PlayButton = PauseButton;
NSLog (#"This is playing");
} else if (playbackState == MPMusicPlaybackStateStopped) {
self.textLabel.text = #"Play";
self.PlayButton = PlayButton;
[self.player stop];
}
}
Any ideas?
I figured this out. I just needed to add the code below in viewDidLoad
if ([musicPlayer playbackState] == MPMusicPlaybackStatePlaying) {
[playPauseButton setImage:[UIImage imageNamed:#"pauseButton.png"] forState:UIControlStateNormal];
} else {
[playPauseButton setImage:[UIImage imageNamed:#"playButton.png"] forState:UIControlStateNormal];
}
I am experimenting this issue while trying to open a webpage in an ios app. Before ios7 it was working perfect but now we are upgrading our app and this is the only serious problem we have.
About this problem I found that it is produced when a call is made twice. And I think this is what is happening here because if I write a NSLog text in didFailLoadWithError, it shows twice.
I tried ignoring the error but the loading circle is shown ethernally and webpage not loads.
I paste here my code, maybe you can help us or give us a clue.
#import "WebPoiViewController.h"
#import "FavoriteManager.h"
#interface WebPoiViewController ()
#end
#implementation WebPoiViewController
#synthesize webView,urlStr, activityIndicator,title2,poi=_poi,position=_position;
- (void)viewDidLoad { //We have a NIB file in play here, so I dropped the loadView here. Just make sure that your loadView is not getting called twice!
[super viewDidLoad];
if (self.poi!=nil){
self.position = [[FavoriteManager sharedInstance] isPoiInFavoriteList:self.poi];
if (self.position==-1){
UIButton *button1 = [[UIButton alloc] init];
button1.frame=CGRectMake(0,0,30,30);
[button1 setBackgroundImage:[UIImage imageNamed: #"Favorites_icon_inactive.png"] forState:UIControlStateNormal];
[button1 addTarget:self action:#selector(makeFavorite:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button1];
//self.navigationItem.rightBarButtonItem= [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:#"Favorites_icon_inactive.png"] style: UIBarButtonItemStylePlain target:self action:#selector(makeFavorite:)];
} else {
UIButton *button1 = [[UIButton alloc] init];
button1.frame=CGRectMake(0,0,30,30);
[button1 setBackgroundImage:[UIImage imageNamed: #"Favorites_icon.png"] forState:UIControlStateNormal];
[button1 addTarget:self action:#selector(deleteFavorite:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button1];
//self.navigationItem.rightBarButtonItem= [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:#"Favorites_icon.png"] style: UIBarButtonItemStylePlain target:self action:#selector(deleteFavorite:)];
}
}
if (nil!=title2&& ![title2 isEqualToString:#""]){
self.title=self.title2;
}
[self loadView];
}
- (IBAction)makeFavorite:(id)sender {
self.position=[[FavoriteManager sharedInstance] addFavotitePOI:self.poi];
UIButton *button1 = [[UIButton alloc] init];
button1.frame=CGRectMake(0,0,30,30);
[button1 setBackgroundImage:[UIImage imageNamed: #"Favorites_icon.png"] forState:UIControlStateNormal];
[button1 addTarget:self action:#selector(deleteFavorite:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button1];
}
- (IBAction)deleteFavorite:(id)sender {
[[FavoriteManager sharedInstance] deleteFavotitePOIat:self.position];
self.position=-1;
UIButton *button1 = [[UIButton alloc] init];
button1.frame=CGRectMake(0,0,30,30);
[button1 setBackgroundImage:[UIImage imageNamed: #"Favorites_icon_inactive.png"] forState:UIControlStateNormal];
[button1 addTarget:self action:#selector(makeFavorite:) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button1];
}
- (void)loadView {
UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.view = contentView;
CGRect webFrame = [[UIScreen mainScreen] applicationFrame];
webFrame.origin.y = 0.0f;
webView = [[UIWebView alloc] initWithFrame:webFrame];
webView.backgroundColor = [UIColor blueColor];
webView.scalesPageToFit = YES;
webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
webView.delegate = self;
if([webView respondsToSelector:#selector(scrollView)]){
webView.scrollView.bounces = NO;
}
[self.view addSubview: webView];
if (nil!=self.urlStr && ![urlStr isEqualToString:#""]){
NSLog(#"NO ES NIL");
//[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]]];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityIndicator.frame = CGRectMake(0.0, 0.0, 40.0, 40.0);
//activityIndicator.center = self.view.center;
activityIndicator.center = CGPointMake(self.view.frame.size.width/2,self.view.frame.size.height/2);
[self.view addSubview: activityIndicator];
} else{
[webView loadHTMLString:#"<html><center><br /><br /><font size=+5>No info<br /><br /></font></center></html>" baseURL:nil];
}
}
#pragma mark WEBVIEW Methods
- (void)webViewDidStartLoad:(UIWebView *)myWebView
{
// starting the load, show the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[activityIndicator startAnimating];
}
- (void)webViewDidFinishLoad:(UIWebView *)myWebView
{
// finished loading, hide the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[activityIndicator stopAnimating];
}
- (void)webView:(UIWebView *)myWebView didFailLoadWithError:(NSError *)error
{
if([error code] == NSURLErrorCancelled) return; // Ignore this error
NSLog(#"FAIL");
// load error, hide the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// report the error inside the webview
NSString* errorString = [NSString stringWithFormat:
#"<html><center><br /><br /><font size=+5 color='red'>Error<br /><br />Your request %#</font></center></html>",
error.localizedDescription];
[webView loadHTMLString:errorString baseURL:nil];
}
- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
}
- (BOOL)shouldAutorotate {
return [self.navigationController shouldAutorotate];
}
- (NSUInteger)supportedInterfaceOrientations {
return [self.navigationController supportedInterfaceOrientations];
}
#end
I solved it by myself. I want to share the answer because maybe it helps others with the same problem.
I just added in didFailWithError this code:
- (void)webView:(UIWebView *)myWebView didFailLoadWithError:(NSError *)error
{
if([error code] != NSURLErrorCancelled) // only goes in if it is not -999
{
// load error, hide the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// report the error inside the webview
NSString* errorString = [NSString stringWithFormat:
#"<html><center><br /><br /><font size=+5 color='red'>Error<br /><br />Your request %#</font></center></html>",
error.localizedDescription];
[webView loadHTMLString:errorString baseURL:nil];
}
else{
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr] ]];
}
}
Now, if it fail, it tries to repeat the load until it loads. It can be improved by using a counter. Just trying it 5 or 10 times and not more like mine.
I have a UITableView with CustomCell. Whenever UITableView is in editing mode i have following code in CustomCell.
- (void)willTransitionToState:(UITableViewCellStateMask)state{
[super willTransitionToState:state];
if (state == UITableViewCellStateShowingEditControlMask)
{
self.delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[self.delBtn setFrame:CGRectMake(10, 15, 25, 25)];
[self.delBtn setImage:[UIImage imageNamed:#"noSelection.png"] forState:UIControlStateNormal];
buttonCurrentStatus = YES;
[self.delBtn addTarget:self action:#selector(delBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.delBtn];
}
else
{
if(self.delBtn)
{
[self.delBtn removeFromSuperview];
self.delBtn = nil;
}
} }
- (void)delBtnPressed:(id)sender {
if (buttonCurrentStatus == NO)
{
buttonCurrentStatus = YES;
[self.delBtn setImage:[UIImage imageNamed:#"noSelection.png"] forState:UIControlStateNormal];
}
else
{
buttonCurrentStatus = NO;
[self.delBtn setImage:[UIImage imageNamed:#"selection.png"] forState:UIControlStateNormal];
} }
Now how can i get indexPath from CustomCell of UITableview ?
You can use UITableView indexPathForCell:.
Obviously, for that you'll need a reference to the table inside the cell class. If you want to make it a property of your cell, be sure to make it weak to avoid a reference cycle.
I have found the best way of doing this is to create Delegate/Protocol on cell. Make the delegate the ViewController and pass it in. Then you can call indexPathForCell on the tableview at that point. Example below.
- (void)willTransitionToState:(UITableViewCellStateMask)state{
[super willTransitionToState:state];
if (state == UITableViewCellStateShowingEditControlMask)
{
self.delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[self.delBtn setFrame:CGRectMake(10, 15, 25, 25)];
[self.delBtn setImage:[UIImage imageNamed:#"noSelection.png"] forState:UIControlStateNormal];
buttonCurrentStatus = YES;
[self.delBtn addTarget:self action:#selector(delBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.delBtn];
}
else
{
if(self.delBtn)
{
[self.delBtn removeFromSuperview];
self.delBtn = nil;
}
} }
- (void)delBtnPressed:(id)sender {
if (buttonCurrentStatus == NO)
{
buttonCurrentStatus = YES;
[self.delBtn setImage:[UIImage imageNamed:#"noSelection.png"] forState:UIControlStateNormal];
}
else
{
buttonCurrentStatus = NO;
[self.delBtn setImage:[UIImage imageNamed:#"selection.png"] forState:UIControlStateNormal];
}
if ([self.delegate respondsToSelector:(customCelldelBtnPressed:)]) {
[self.delegate customCelldelBtnPressed:self];
}
}
// of course you will need to actually create the delegate or protocol and implement it on the view controller.
i am using MPMovieplayerController for playing video, while im clicking some other button i.e i want to pause my video wherever its playing again. i click play means i want to play while its pausing.But for me now when i click button means my video was stopped.But i want to pause instead of stop.
My sample code here
- (IBAction) playvideo
{
NSURL *url = [NSURL URLWithString:#"http://xyz/video1.mp4"];
movieplayer = [[[MPMoviePlayerController alloc]initWithContentURL:url] retain];
movieplayer.view.frame=CGRectMake(25,54,658,460);
[self.view addSubview:movieplayer.view];
[movieplayer play];
}
-(void)buttononclick
{
[movieplayer pause];
[movieplayer.view removeFromSuperview];
for (int i = 0; i < 13; i++)
{
CGRect frame;
frame.origin.x = 150 * i;
frame.origin.y = 0;
frame.size = CGSizeMake(140, self.scrollView.frame.size.height);
[scrollView setShowsHorizontalScrollIndicator:NO];
UIImageView *temp1 = [[UIImageView alloc] initWithFrame:CGRectMake(25, 7, 75, 75)];
[temp1 setImage:[UIImage imageNamed:#"sti15.png"]];
[self.scrollView addSubview:temp1];
UIImageView *temp2 = [[UIImageView alloc] initWithFrame:CGRectMake(110, 7, 75, 75)];
[temp2 setImage:[UIImage imageNamed:#"sti16.png"]];
[self.scrollView addSubview:temp2];
UIImageView *temp3 = [[UIImageView alloc] initWithFrame:CGRectMake(195, 7, 75, 75)];
[temp3 setImage:[UIImage imageNamed:#"sti17.png"]];
[self.scrollView addSubview:temp3];
}
self.scrollView.contentSize = CGSizeMake(165 * 10, self.scrollView.frame.size.height);
self.scrollView.pagingEnabled=0;
}
- (void)viewDidDisappear:(BOOL)animated
{
// [self setDescText:nil];
[super viewDidDisappear:animated];
[movieplayer pause];
[movieplayer.view removeFromSuperview];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if ((movie.playbackState==MPMoviePlaybackStateStopped)||(movie.playbackState==MPMoviePlaybackStatePaused))
{
[movie play];
}
else
{
[movie pause];
}
}
Try this Code , it will Work
Check out the notifications for MPMoviePlaybackStatePlaying, MPMoviePlaybackStateStopped, MPMoviePlaybackStatePaused, and MPMoviePlaybackStateInterrupted.
Something like:
MPMoviePlayerController *player = notification.object;
/* Playback is currently stopped. */
if (player.playbackState == MPMoviePlaybackStateStopped)
{
NSLog(#"MPMoviePlaybackStateStopped");
}
/* Playback is currently under way. */
else if (player.playbackState == MPMoviePlaybackStatePlaying)
{
NSLog(#"MPMoviePlaybackStatePlaying");
}
/* Playback is currently paused. */
else if (player.playbackState == MPMoviePlaybackStatePaused)
{
NSLog(#"MPMoviePlaybackStatePaused");
}
You can wire up your target action something like this:
if ((_moviePlayer.playbackState == MPMoviePlaybackStateStopped) || (_moviePlayer.playbackState == MPMoviePlaybackStatePaused)) {
[_moviePlayer play];
} else {
[_moviePlayer pause];
}
you can add target to the play/pause button.
but first you need to catch the button of the mpmovieplayerview.
step 1 list the button. method reference from here
call this method from when the button appear(the video is ready).
But remember, this will also catch the full screen button and airplay button.(if available)
- (void)CatchSubviewsOfView:(UIView *)view {
// Get the subviews of the view
NSArray *subviews = [view subviews];
for (UIView *subview in subviews) {
// Do what you want to do with the subview
NSLog(#"%#", subview);
if(subview isKindOfClass:[UIButton class]]){
// add your target here
[subview addTarget:self action:#selector(extraAction:) forControlEvents:UIControlEventTouchUpInside];
}
// List the subviews of subview
[self listSubviewsOfView:subview];
}
}
step 2 implement the action
-(IBAction)extraAction:(id)sender{
NSLog(#"some extraAction");
}
call the catch method sample.
[self CatchSubviewOfView:movieplayer.view];
After i implemented a code for give an check image for a button but i want to give check image for no of buttons.
note: if i click on one button check image can be displayed and the same time i click on another button check image displayed on that particular button and previous button comes normal position.
i implement the code for single button here like this.
-(void) setChecked:(BOOL) check
{
_checked = check;
if( _checked )
{
UIImage* img = [UIImage imageNamed:#"btn_check_on.png"];
[self setImage:img forState:UIControlStateNormal];
}
else
{
UIImage* img = [UIImage imageNamed:#"bread_Wheat_rectangle.png"];
[self setImage:img forState:UIControlStateNormal];
}
}
The above code is executed successfully but how to use this code for no of buttons.
please suggest any tutorial regarding my problem
This is how I have implemented it for one button. You can use it for more buttons too.
-(IBAction)ButtonAction
{
if (Flag==0)
{
Flag=1;
[myButton setImage:[UIImage imageNamed:#"checkbox-filled.png"] forState:UIControlStateNormal];
}
else
{
[myButton setImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
Flag=0;
}
}
Note : If you want only one button to get checked Just set all other buttons image as checkbox.png and the selected one's checkbox-filled.png.
EDIT
You can make a class for checkbox and then use it. Here is the code...
CheckButton.h
#import <Foundation/Foundation.h>
#interface CheckButton : UIButton {
BOOL _checked;
int chkButtonClickVal;
}
#property (nonatomic, setter=setChecked:) BOOL checked;
-(void) setChecked:(BOOL) check;
-(int)chkButtonClickVal;
#end
CheckButton.m
#import "CheckButton.h"
#implementation CheckButton
#synthesize checked = _checked;
-(id) init
{
if( self=[super init] )
{
chkButtonClickVal=0;
self.checked = NO;
[self addTarget:self action:#selector(OnCheck:) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
-(void) awakeFromNib
{
self.checked = NO;
[self addTarget:self action:#selector(OnCheck:) forControlEvents:UIControlEventTouchUpInside];
}
-(void) dealloc
{
chkButtonClickVal=0;
[super dealloc];
}
-(void) setChecked:(BOOL) check
{
_checked = check;
if( _checked )
{
UIImage* img = [UIImage imageNamed:#"checkbox-checked.png"];
[self setImage:img forState:UIControlStateNormal];
chkButtonClickVal=1;
}
else
{
UIImage* img = [UIImage imageNamed:#"checkbox.png"];
[self setImage:img forState:UIControlStateNormal];
chkButtonClickVal=2;
}
//NSLog(#"%d",chkButtonClickVal);
}
-(int)chkButtonClickVal
{
return chkButtonClickVal;
}
-(void) OnCheck:(id) sender
{
self.checked = !_checked;
}
#end
I have done it in same way. Try you'll be able to achieve it.
Good Luck :)
After long practicing this problem we can use switch cases it can be done very easily
switch (currenttagvalue) {
case 1:
[level1 setImage:[UIImage imageNamed:#"one_time_selected.png"] forState:UIControlStateNormal];
[level2 setImage:[UIImage imageNamed:#"ic_launcher.png"] forState:UIControlStateNormal];
[level3 setImage:[UIImage imageNamed:#"bread_sourdough_rectangle.png"] forState:UIControlStateNormal];
}
in this level is "IBOutlet UIButton level1;"
And then i implement so more buttons