从AppDelegate发送通知到ViewController [英] Send a notification from AppDelegate to ViewController
问题描述
需要您的帮助.我将这些Delegate方法实现到AppDelegate.m:
need your help. I implement these Delegate Method to the AppDelegate.m:
-(BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
if (url != nil && [url isFileURL]) {
//Valid URL, send a message to the view controller with the url
}
else {
//No valid url
}
return YES;
但是现在,我需要的URL不是在AppDelegate中,而是在ViewController中.我如何发送" URL或如何将这些Delegate方法实现到ViewController?
But now, I need the URL not in the AppDelegate but in my ViewController. How I can "send" them the url or how I can implement these Delegate Method to the ViewController?
推荐答案
您可以使用NSNotificationCenter
,如下所示:
you can use NSNotificationCenter
as shown below:
首先在您的应用程序委托中将Notification发布为:
Firstly post Notification in your app delegate as :
NSDictionary *_dictionary=[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:@"%d",newIndex],nil] forKeys:[NSArray arrayWithObjects:SELECTED_INDEX,nil]];
[[NSNotificationCenter defaultCenter] postNotificationName:SELECT_INDEX_NOTIFICATION object:nil userInfo:_dictionary];
然后将您要观察此通知的ViewController注册为
then register the ViewController you want to observe this notification as
/***** To register and unregister for notification on recieving messages *****/
- (void)registerForNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(yourCustomMethod:)
name:SELECT_INDEX_NOTIFICATION object:nil];
}
/*** Your custom method called on notification ***/
-(void)yourCustomMethod:(NSNotification*)_notification
{
[[self navigationController] popToRootViewControllerAnimated:YES];
NSString *selectedIndex=[[_notification userInfo] objectForKey:SELECTED_INDEX];
NSLog(@"selectedIndex : %@",selectedIndex);
}
在ViewDidLoad中将该方法调用为:
call this method in ViewDidLoad as :
- (void)viewDidLoad
{
[self registerForNotifications];
}
,然后在UnLoad上通过调用以下方法删除此观察器:
and then on UnLoad remove this observer by calling this method :
-(void)unregisterForNotifications
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:SELECT_INDEX_NOTIFICATION object:nil];
}
-(void)viewDidUnload
{
[self unregisterForNotifications];
}
希望它对您有帮助.
这篇关于从AppDelegate发送通知到ViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!