0

I have a online radio player with tab footer functionality. The first tab contains player, second the website and third some message box. Now whats happening is that when I play the song in first footer, and then going to another footer, and coming back to first footer, the song is getting started again. Here is the code:

FirstViewController.m

#import "FirstViewController.h"
CM_EXPORT const CMTime kCMTimeZero;
@interface FirstViewController ()
@end


@implementation FirstViewController
@synthesize  metadatas;
@synthesize toggleButton;
@synthesize slider;
@synthesize mpVolumeView = _mpVolumeView;
@synthesize viewVolume;

- (void)viewDidLoad
{

    toggleIsOn=TRUE;

    MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:self.viewVolume.bounds] ;

    [self.viewVolume addSubview:volumeView];

    [volumeView sizeToFit];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(IBAction)playButtonPressed:(id)sender
{

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:TRUE forKey:@"FirstPlay"];
    [defaults setBool:YES forKey:@"alertShown"];

    if(toggleIsOn){

        toggleIsOn=!toggleIsOn;

        player = nil;
        NSString *stringurl = @"";
        stringurl = @"http://majestic.wavestreamer.com:6221/listen.pls";
        NSURL *url = [NSURL URLWithString:stringurl];
        asset = [AVURLAsset URLAssetWithURL:url options:nil];
        playerItem = [AVPlayerItem playerItemWithAsset:asset];
        player = [AVPlayer playerWithPlayerItem:playerItem];
        player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
        [playerItem addObserver:self forKeyPath:@"timedMetadata" options:NSKeyValueObservingOptionNew context:nil];
        [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
        [player play];

        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(audioSessionInterrupted:) name:AVAudioSessionInterruptionNotification object:nil];

        [self.toggleButton setImage:[UIImage imageNamed:@"reload.png"] forState:UIControlStateNormal];
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
        [[AVAudioSession sharedInstance] setActive: YES error: nil];
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    }
    else {

        [self.toggleButton setImage:[UIImage imageNamed:@"playMusic.png"] forState:UIControlStateNormal];
        self->player.rate=0.0;
        toggleIsOn=!toggleIsOn;        
    }
}
- (void)audioSessionInterrupted:(NSNotification *)notification
{

    NSNumber *interruptionType = [[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey];
    NSNumber *interruptionOption = [[notification userInfo] objectForKey:AVAudioSessionInterruptionOptionKey];

    switch (interruptionType.unsignedIntegerValue) {
        case AVAudioSessionInterruptionTypeBegan:{
           // [self.toggleButton setImage:[UIImage imageNamed:@"playMusic.png"] forState:UIControlStateNormal];

            // • Audio has stopped, already inactive
            // • Change state of UI, etc., to reflect non-playing state
        } break;
        case AVAudioSessionInterruptionTypeEnded:{
            // • Make session active
            // • Update user interface
            // • AVAudioSessionInterruptionOptionShouldResume option
            if (interruptionOption.unsignedIntegerValue == AVAudioSessionInterruptionOptionShouldResume) {
                // Here you should continue playback.
                [player play];
            }
        } break;


        default:
            break;
    }

}

- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)audioPlayer
{
    [player pause];
}
-(void)audioRecorderEndInterruption:(AVAudioRecorder *)audioPlayer
{
    [player play];

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:TRUE forKey:@"alertShown"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];

    internetReachable = [Reachability reachabilityForInternetConnection];
    [internetReachable startNotifier];

    // check if a pathway to a random host exists
    hostReachable = [Reachability reachabilityWithHostName:@"www.apple.com"];
    [hostReachable startNotifier];


}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
                        change:(NSDictionary *)change context:(void *)context {

    [playerItem removeObserver:self forKeyPath:keyPath];


    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItem *pItem = (AVPlayerItem *)object;
        if (pItem.status == AVPlayerItemStatusReadyToPlay)
        {
            metadatas.text = @"";
        }
    }
    if ([keyPath isEqualToString:@"timedMetadata"]) {
        for (AVAssetTrack *track in playerItem.tracks) {
            for (AVPlayerItemTrack *item in player.currentItem.tracks) {
                if ([item.assetTrack.mediaType isEqual:AVMediaTypeAudio]) {
                    NSArray *meta = [playerItem timedMetadata];
                    for (AVMetadataItem *metaItem in meta) {

                        NSString *source = metaItem.stringValue;
                        metadatas.text = source;
                    }
                }
            }
        }
    }

    [self.toggleButton setImage:[UIImage imageNamed:toggleIsOn ? @"playMusic.png" :@"stop.png"] forState:UIControlStateNormal];

}

-(IBAction) sliderChanged:(id)sender
{
    player.volume = slider.value;

}
-(void) checkNetworkStatus:(NSNotification *)notice
{
    // called after network status changes
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    switch (internetStatus)
    {
        case NotReachable:
        {
            NSLog(@"The internet is down.");
            NSLog(@"%d",[defaults boolForKey:@"alertShown"]);
            BOOL isAlertShown = [defaults boolForKey:@"alertShown"];
            if(isAlertShown)
           {

               [self showAlert];
           }

            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"The internet is working via WIFI.");


            BOOL isFirstTimePlayed = [defaults boolForKey:@"FirstPlay"];
            if(isFirstTimePlayed)
            {
                [self playButtonPressed:nil];

            }

            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"The internet is working via WWAN.");
            [self playButtonPressed:nil];

            break;
        }
    }

   }
-(void)showAlert
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:FALSE forKey:@"alertShown"];

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Alert" message: @"You have lost data connectivity. Please wait while we try to establish the connection again." delegate: nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];

}
- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}
@end

SecondViewController.m

#import "SecondViewController.h"
#import "MBProgressHUD.h"
@interface SecondViewController ()

@end

@implementation SecondViewController

- (void)viewDidLoad
{
    [super viewDidLoad];



    webView = [[UIWebView alloc] init];
    [webView setFrame:self.view.frame];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.radiomalayalam.net"]]];
    [self.view addSubview:webView];
    CGSize contentSize = webView.scrollView.contentSize;
    CGSize viewSize = self.view.bounds.size;

    float rw = viewSize.width / contentSize.width;

    webView.scrollView.minimumZoomScale = rw;
    webView.scrollView.maximumZoomScale = rw;
    webView.scrollView.zoomScale = rw;
    webView.scalesPageToFit = YES;
    [webView setDelegate:self];

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"Loading";
    // you can implement any int/float value in context of what scale you want to zoom in or out
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)twoFingerPinch:(UIPinchGestureRecognizer *)recognizer
{
    NSLog(@"Pinch scale: %f", recognizer.scale);
    CGAffineTransform transform = CGAffineTransformMakeScale(recognizer.scale, recognizer.scale);
    // you can implement any int/float value in context of what scale you want to zoom in or out
    webView.transform = transform;
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{

    [MBProgressHUD hideHUDForView:self.view animated:YES];

}
- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}
@end

ThirdViewController.m

#import "ThirdViewController.h"

@interface ThirdViewController ()

@end

@implementation ThirdViewController
@synthesize mBodyText,mSubjectLabel;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

        [mBodyText setDelegate:self ];
        [mSubjectLabel setDelegate:self];

        }


    return self;
}
- (IBAction)hidekeyBoard:(id)sender {

    [mSubjectLabel resignFirstResponder];


}

- (IBAction)hidekeyBoard2:(id)sender
{

}


- (void)viewDidLoad
{
    [super viewDidLoad];


       // Do any additional setup after loading the view.
}

- (void)registerForKeyboardNotifications {

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeShown:)
                                                 name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}


- (void)keyboardWillBeShown:(NSNotification*)aNotification {

    CGRect backgroundViewFrame =  self.view.frame;

    if  (backgroundViewFrame.origin.y >= 0)
    {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3];

        backgroundViewFrame.origin.y -= 100;
        self.view.frame = backgroundViewFrame;

        [UIView commitAnimations];
    }
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification {

    CGRect backgroundViewFrame = self.view.frame;

    //    if  (backgroundViewFrame.origin.y < 130)
    {
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3];

        backgroundViewFrame.origin.y += 100;
        self.view.frame = backgroundViewFrame;

        [UIView commitAnimations];
    }
}

- (void)textViewDidChange:(UITextView *)textView {

    }

- (void) resignIfResponder {

    if ([mBodyText isFirstResponder])
        [mBodyText resignFirstResponder];

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)onSendMail:(id)sender {

    NSLog(@"%@",mSubjectLabel.text);
    NSMutableString *subject  = [NSMutableString string];
    [subject appendString:mSubjectLabel.text];

    NSMutableString *mailbody  = [NSMutableString string];
    [mailbody appendString:mBodyText.text];

    NSString *recipients = [NSString stringWithFormat:@"mailto:test@test.com?&subject=%@!",subject];

    NSString *body = [NSString stringWithFormat:@"&body=%@!",mailbody];;

    NSString *emailString = [NSString stringWithFormat:@"%@%@", recipients, body];

    emailString = [emailString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    if ([[UIApplication sharedApplication] canOpenURL:[ NSURL URLWithString:@"mailto:"]])
    {
        NSLog(@"Can Send");
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:emailString]];

    }



}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];

    if (![[touch view] isKindOfClass:[UITextField class]]) {
        [self.view endEditing:YES];
    }
    [super touchesBegan:touches withEvent:event];
}
- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}


@end

Please ask if I need to paste any more files. I am unable to understand how to remove restarting of songs. Please help. Thanx.

Piyush Dubey
  • 2,416
  • 1
  • 24
  • 39
ZooZ
  • 309
  • 5
  • 19
  • I couldn't see what objects control the playing of the song, but it's fairly clear that iOS removes unused tabs in order to conserve resources. You need to keep these "song objects" elsewhere (in a model object) outside of the tab in order to get around this issue. – trojanfoe Jan 15 '14 at 13:35
  • Like .? I am unable to understand what to do. Can you please help.? Shall I paste all .h files also.? – ZooZ Jan 15 '14 at 13:37
  • 1
    Put the "song objects" in some global array or something, not within the view controller. – trojanfoe Jan 15 '14 at 13:37
  • If I do in firstViewcontroller.h instead of .m, will that work.? – ZooZ Jan 15 '14 at 14:17
  • No. those objects don't belong in the view controller, which should merely manage the presentation of data (and capture of input). The data itself should be kept elsewhere (and by "data", in this case, I mean the song data and the object which controls its playing). – trojanfoe Jan 15 '14 at 14:20
  • I see that you're overriding `viewWillAppear:` and `viewDidAppear:` in your FirstViewController. So essentially, every time the first tab is tapped, that code will be run. So is there something in that code that is causing your songs to restart? – hgwhittle Jan 15 '14 at 14:30
  • You can see the code in WillAppear and DidAppear.. Please tell me what modification to do.. – ZooZ Jan 15 '14 at 15:20

0 Answers0