iOS开发之SFSafariViewController

2023-03-16 21:27:57 浏览数 (1)

介绍

  • SFSafariViewController iOS 9 之后推出的一种 UIViewController,用于加载与显示 Web 内容,页面展示类似 Safari 浏览器的效果。
  • 需要导入SafariServices模块。

案例

代码语言:javascript复制
import SafariServices
import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        showSafariViewController()
    }

    // MARK: 显示SFSafariViewController
    func showSafariViewController() {
        // URL
        let url = URL(string: "https://www.baidu.com")
        // 创建SFSafariViewController
        let safariViewController = SFSafariViewController(url: url!)
        // 设置代理
        safariViewController.delegate = self
        // 显示
        present(safariViewController, animated: true, completion: nil)
    }
}

extension ViewController: SFSafariViewControllerDelegate {
    // MARK: 点击左上角的完成
    func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
        print(#function)
    }

    // MARK: 加载完成
    func safariViewController(_ controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) {
        print(#function)
    }
    
    // MARK: 点击右下角调用Safari浏览器打开
    func safariViewControllerWillOpenInBrowser(_ controller: SFSafariViewController) {
        print(#function)
    }
}

注意:SFSafariViewController 只能加载 HTTP/HTTPS 的 URL。

0 人点赞