Marv
Marv

Reputation: 153

Send a notification from AppDelegate to ViewController

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;

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?

Upvotes: 0

Views: 7950

Answers (2)

Buntylm
Buntylm

Reputation: 7363

You can post a local notification like this, where notification name will be used by the receiver to subscribe.

[[NSNotificationCenter defaultCenter] 
    postNotificationName:@"Data" 
    object:nil];

And in your viewController subscribe the notification.

[[NSNotificationCenter defaultCenter] 
    addObserver:self 
    selector:@selector(getData:) 
    notificationName:@"Data" 
    object:nil];

- getData:(NSNotification *)notification {
    NSString *tappedIndex = [[_notification userInfo] objectForKey:@"KEY"];
}

For More About the NSNotificationCenter Can go with this link

Upvotes: 6

Nishant Tyagi
Nishant Tyagi

Reputation: 9913

you can use NSNotificationCenter as shown below:

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];

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);

}

call this method in ViewDidLoad as :

- (void)viewDidLoad
{

    [self registerForNotifications];
}

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];
}

Hope it helps you.

Upvotes: 12

Related Questions