How to show a UIAlertView when a link is fired in the UITextField?

0

Problem scenario:

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

    
asked by anonymous 30.09.2014 / 15:40

1 answer

1

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

- (void)viewDidLoad {

    [super viewDidLoad];

    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(100, 100, 200, 50)];
    textView.text = @"http://www.google.com.br";
    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 the alert view and return NO, so as not to let the system interact with the URL (in this case open it in the browser). Now implement the UIAlertView delegate to receive the click events 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];
        }
    }
}
    
30.09.2014 / 16:56