2016-08-17 54 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]; 
} 
相關問題