从UITextView自动检测到的链接打开带有SFSafariViewController的网站

Adr*_*ian 6 objective-c mobile-safari uiviewcontroller ios

我有一个UIViewControllerUITextView的是自动检测到其超文本链接.它工作正常,但我会用SFSafariViewController打开链接,所以我留在我的应用程序"内部",而不是打开一个单独的浏览器,这是"开箱即用"的行为.

我已经采取了下面的步骤,但网站仍然打开一个单独的Safari浏览器,而不是在我的应用程序内.我没有收到任何错误或警告,但检测到的网站仍在单独的浏览器中打开,而不是在我的应用程序中.该UITextViewDelegate方法似乎没有被调用(我将一个日志语句放入检查).

我看着,UITextViewDelegate我想我想用这种方法来打开被网络检测到的网站UITextView:

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    // Fill code in here to use SFSafariViewController
    return YES;
}
Run Code Online (Sandbox Code Playgroud)

到目前为止我做了什么:

1)导入SafariServices,制作委托声明,并在MyViewController中声明委托属性.H

@import SafariServices;

@interface MyViewController : UIViewController <UITextViewDelegate, SFSafariViewControllerDelegate>

@property(nonatomic, weak, nullable) id< SFSafariViewControllerDelegate, SFSafariViewControllerDelegate > delegate;
Run Code Online (Sandbox Code Playgroud)

2)在我的.m文件中添加了一个委托部分,并尝试从上面的存根中填写此方法:

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    SFSafariViewController *websiteToOpen = [[SFSafariViewController alloc]initWithURL:URL entersReaderIfAvailable:YES];
    websiteToOpen.delegate = self;
    [self presentViewController:websiteToOpen animated:YES completion:nil];
    return YES;
}
Run Code Online (Sandbox Code Playgroud)

我确信这是100%我这么做,但我无法超越终点线.我错过了什么?

Tun*_*Fam 9

万一有人在寻找Swift 3的实现.

有效的解决方案:

1.进口Safari服务

import SafariServices
Run Code Online (Sandbox Code Playgroud)

2.创建属性文本,添加链接到文本,将字符串分配给textView

let myLink = "google.com"
let myText = "here is my link: \(myLink)"
let myAttributedText = NSMutableAttributedString(string: myText)
let rangeOfMyLink = myText.range(of: myLink)
if rangeOfMyLink.location != NSNotFound {
    myAttributedText.addAttributes([NSLinkAttributeName: myLink], range: rangeOfMyLink)
}
myTextView.attributedText = myAttributedText
myTextView.delegate = self
Run Code Online (Sandbox Code Playgroud)

3.将代表添加到VC:

class MyViewController: UIViewController, UITextViewDelegate
Run Code Online (Sandbox Code Playgroud)

4.添加委托方法:

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
    let safariVC = SFSafariViewController(url: URL)
    present(safariVC, animated: true, completion: nil)
    return false
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!


小智 3

我正在尝试做同样的事情,但遇到不同的问题。

首先,您需要设置文本视图的委托才能delegate触发该方法。我在 viewDidLoad 中执行此操作:

myTextView.delegate = self;
Run Code Online (Sandbox Code Playgroud)

然后,告诉您UITextView 不要与该 URL 交互:

- (BOOL)textView:(UITextView *)textView 
        shouldInteractWithURL:(NSURL *)url 
        inRange:(NSRange)characterRange
{
    [self presentViewController:websiteToOpen animated:YES completion:nil];
    return NO;
}
Run Code Online (Sandbox Code Playgroud)

有了这个,我可以呈现 safari 视图控制器,尽管它是空的,即没有内容,也没有“完成”按钮。所以我做错了其他事情......