How do I extract a URL within a UITextView in Xcode?

时间:2015-06-25 18:37:06

标签: ios xcode

I'm trying to use the UITextView delegate method(textView:shouldInteractWithURL:inRange:) to override the default behavior of links in my textView opening in Safari.

I know I should create the webView I want to instantiate and pass the URL to it, but I don't know how to pass the URL to the webView.

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

//Do something with the URL
NSURL *url = [[NSURL alloc] initWithString:self.sourceInformation.text.?];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
WebViewController *sourceWebViewController = [[self storyboard] instantiateViewControllerWithIdentifier:@"WebViewController"];

[sourceWebViewController.webView loadRequest:request];

sourceWebViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

return NO;

}

Is there some property on UITextView that hold the URL? I looked at the header file but didn't see one.

If anyone can help, thanks.

1 个答案:

答案 0 :(得分:0)

Try this, -(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange { [self performSelector:@selector(loadWebView) withObject:nil afterDelay:1] ; return NO; } -(void)loadWebView { NSURL *url = [[NSURL alloc] initWithString:self.sourceInformation.text.?]; if([[UIApplicaiton sharedApplication] canOpenURL:url]) { NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; WebViewController *sourceWebViewController = [[self storyboard] instantiateViewControllerWithIdentifier:@"WebViewController"]; [sourceWebViewController.webView loadRequest:request]; sourceWebViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve; } else { NSLog(@"Can not open the URL, check the URL") ; } }