iosobjective-cuialertviewappdelegateuialertviewdelegate

alertView:(UIAlertView *) alertView method not working in Appdelegate


I had set UIAlertView in AppDelegate.m file.

But when I choose the button on the alert view.

-(void) alertView:(UIAlertView *) alertView clickedButtonAtIndex:(NSInteger)buttonIndex

was not working.

I had set UIAlertViewDelegate in the AppDelegate.h file.

and my AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:        (NSDictionary *)launchOptions
        {

         [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];

            NSString *remoteHostName = REACHABILITY_HOST;
            _hostReachability = [Reachability reachabilityWithHostName:remoteHostName];
            [_hostReachability startNotifier];

            return YES;
        }

        - (void) reachabilityChanged:(NSNotification *)note
        {
         if( [Reachability isExistNetwork] == NotReachable)
            {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil         message:@"my message" delegate:nil cancelButtonTitle:@"ok"         otherButtonTitles:@"set",nil];
                [alertView show];

            }

        }

        -(void) alertView:(UIAlertView *) alertView clickedButtonAtIndex:(NSInteger)buttonIndex
        {

            switch (buttonIndex) {

                case 0:
                    NSLog(@"ok!");
                    break;

                    // set
                case 1:

                    NSLog(@"set!");
                    NSURL*url=[NSURL URLWithString:@"prefs:root=WIFI"];
                    [[UIApplication sharedApplication] openURL:url];
                    break;

            }
        }

But the

-(void) alertView:(UIAlertView *) alertView clickedButtonAtIndex:(NSInteger)buttonIndex

was not enter this method.

Have anyone know what happened? thanks.


Solution

  • Your code doesn't correctly set the delegate of the alert view.

    You need to change the following line so that the delegate is the appropriate object (eg, self):

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil         message:@"my message" delegate:nil cancelButtonTitle:@"ok"         otherButtonTitles:@"set",nil];