Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting appdelegate value from viewcontroller

In Appdelegate.h
I imported the playerviewcontroller in both Appdelegate.h and Appdelegate.m files.

  @class PlayerViewController; 
  @property(nonatomic)float volumeDelegate;        

In Appdelegate.m

  @synthesize volumeDelegate;
 - (void)volumeChanged:(NSNotification *)notification
 {
volumeDelegate =1.0
    PlayerViewController *volumeObject=[[PlayerViewController alloc]init];
[volumeObject setVolumeForAVAudioPlayer];
}

In Playerviewcontroller.h

 -(void)setVolumeForAVAudioPlayer;

In Playerviewcontroller.m

@interface PlayerViewController ()
{
AppDelegate *appdelegate;

 }
  -(void)viewDidLoad
  {
  appdelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  }

  -(void)setVolumeForAVAudioPlayer
  {
[appdelegate.sharedplayer  setVolume:appdelegate.volumeDelegate];
NSLog(@"System Volume in player view:  %f",appdelegate.volumeDelegate);
 }

When i run this I get volumeDelegate value as Zero as below.

System Volume in player view:0.000000000

What is the Mistake I'm making here

like image 766
AlgoCoder Avatar asked Aug 23 '13 11:08

AlgoCoder


People also ask

What is the difference between SceneDelegate and AppDelegate?

AppDelegate is responsible for handling application-level events, like app launch and the SceneDelegate is responsible for scene lifecycle events like scene creation, destruction and state restoration of a UISceneSession.

What is AppDelegate in Objective C?

So an app delegate is an object that the application object can use to do certain things like display the first window or view when the app starts up, handle outside notifications or save data when the app goes into the background.


2 Answers

You can access to the AppDelegate object like below

Objective-C

Define it like this:

AppDelegate appDelegate;

Access it like this:

appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

Usage:

- (void)setVolumeForAVAudioPlayer
{
    [appDelegate.sharedplayer  setVolume:appdelegate.volumeDelegate];
    NSLog(@"System Volume in player view:  %f",appDelegate.volumeDelegate);
}

Swift:

Define it like this:

let appDelegate = UIApplication.shared.delegate as! AppDelegate

Usage:

func setVolumeForAVAudioPlayer() 
{
    appDelegate.sharedPlayer.setVolume:appDelegate.VolumeDelegate
    print("System Volume in player view: \(appDelegate.volumeDelegate)")
}
like image 178
Hemang Avatar answered Sep 30 '22 05:09

Hemang


You're initializing the appdelegate member variable in a viewDidLoad, but that method is not called at the moment you call setVolumeForAVAudioPlayer!

You're doing

PlayerViewController *volumeObject=[[PlayerViewController alloc]init];
[volumeObject setVolumeForAVAudioPlayer];

But alloc init doesn't make viewController's view to load! viewDidLoad is not called at all.

like image 35
iHunter Avatar answered Sep 30 '22 05:09

iHunter