2016-08-17 53 views
1

我想从每个视图控制器调用此方法。但我不知道此方法将写入的位置以及我如何调用此方法。来自每个视图控制器的调用方法

-(void)playSound{ 

NSURL *url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]]; 
NSData *data =[NSData dataWithContentsOfURL:url]; 
audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil]; 
audioPlayer.delegate = self; 
[audioPlayer setNumberOfLoops:0]; 
[audioPlayer play]; 
} 
+0

声明中的appdelegate文件 – Birendra

+0

可以提供的例子 –

+0

创建一个单独的NSObject类并粘贴该方法。并把它叫做你想要的任何地方 – Blisskarthik

回答

2

您可以创建一个BaseViewController,并宣布内部BaseViewController.h这种方法和内部BaseViewController.m文件执行,不是设置所有ViewControllerBaseViewController一个孩子。

BaseViewController.h

@interface BaseViewController : UIViewController 

-(void)playSound; 

@end 

BaseViewController.m

@interface BaseViewController() 

@end 

@implementation BaseViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view. 

} 

-(void)playSound { 
    NSURL *url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]]; 
    NSData *data =[NSData dataWithContentsOfURL:url]; 
    audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil]; 
    audioPlayer.delegate = self; 
    [audioPlayer setNumberOfLoops:0]; 
    [audioPlayer play]; 
} 
@end 

现在,在您viewController.h

@interface ViewController : BaseViewController 

@end 

ViewController.m

@interface ViewController() 

@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view. 
    [self playSound]; 
} 
@end 
2

您可以创建一个类别:

@interface UIViewController (UIViewControllerAudio) 

-(void)playSound; 

@end 


@implementation UIViewController (UIViewControllerAudio) 

- (void)playSound{ 
    NSURL *url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]]; 
    NSData *data =[NSData dataWithContentsOfURL:url]; 
    audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil]; 
    audioPlayer.delegate = self; 
    [audioPlayer setNumberOfLoops:0]; 
    [audioPlayer play]; 
} 

@end 

和您可以在您的视图控制器打电话:

[self playSound]; 
2

第1步

创建所述一个BaseViewController

@interface BaseViewController : UIViewController 

- (void) playSound; 

@end 

步骤2

BaseViewController.m

@implementation BaseViewController 

-(void)playSound{ 

NSURL *url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]]; 
NSData *data =[NSData dataWithContentsOfURL:url]; 
audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil]; 
audioPlayer.delegate = self; 
[audioPlayer setNumberOfLoops:0]; 
[audioPlayer play]; 
} 

@end 

步骤3

#import "BaseViewController.h" 

// Notice this class is a subclass of BaseViewController (parent) 
@interface yourViewController : BaseViewController 
@end 

步骤-4

可以调用直接

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 
[self playSound]; 
} 
相关问题