How do I show a Uialertview when a link is triggered in Uitextfield?

Asked

Viewed 50 times

0

Scenario of the problem:

There is a link in a UITextView, when this link is triggered it should open a web page. This part is already working. But I need to show a UIAlertView asking if you really want to open the link in the browser. In case "OK", allow the operation to continue, in case of "Cancel", close the opening of the website.

1 answer

1


Implement the method - (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange; of the delegate of Uitextview:

- (void)viewDidLoad {

    [super viewDidLoad];

    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(100, 100, 200, 50)];
    textView.text = @"http://www.google.com";
    textView.editable = NO;
    textView.selectable = YES;
    [textView setDataDetectorTypes:UIDataDetectorTypeLink];
    textView.delegate = self;
    [self.view addSubview:textView];
}

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {

    url = URL;
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Aviso"
                                                        message:@"Deseja abrir o link?"
                                                       delegate:self
                                              cancelButtonTitle:@"Cancelar"
                                              otherButtonTitles:@"OK", nil];
    [alertView show];
    return NO;
}

In this method you create Alert view and return NO, to not let the system interact with the URL (in this case open it in the browser). Now implement the Uialertview delegate to receive the events by clicking on the buttons and open the URL:

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

    if (buttonIndex == 1) {
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}
  • Very good explanation!! It worked!! Thank you @Rafaelleão

Browser other questions tagged

You are not signed in. Login or sign up in order to post.