介绍
- SFSafariViewController iOS 9 之后推出的一种 UIViewController,用于加载与显示 Web 内容,页面展示类似 Safari 浏览器的效果。
- 需要导入
SafariServices
模块。
案例
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。