iOS開發之SFSafariViewController

介紹

  • 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。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容