今回は、iOSアプリでWEBページを表示するためのSFSafariViewControllerの使い方について説明します。
まずはiOSプロジェクトを作成する必要がありますので、作成しましょう。
こちらに詳細がありますので、必要な方は参考にしてください。
- swift 5.2.4
- Xcode 11.6
- macOS 10.15.6 Catalina
- iOS 14.0.1
SFSafariViewController表示準備
まずは SFSafariViewController
を表示するための準備として導線を作っていきましょう。
今回はボタンを押した時に SFSafariViewController
を起動するようにしたいと思います。
そのためまずはボタンを配置していきますが、詳細な UIButton
の使い方についてはこちらを参考ください!
ボタンアクションを定義
まずは UIButton
をストーリーボード上に配置します。
今回はButtonのタイトルを「SFSafariViewControllerを表示する」としておきました。

次にアクションを定義するためにUIButtonに対してCtrl+ドラッグで ViewController
へと引っ張っていきます。
今回はボタンアクションの関数名を tappedButton
としました。

それではきちんとボタンアクションが取れているかを確認するために print
関数を使ってみましょう。
@IBAction func tappedButton(_ sender: Any) {
print("show SFSafariViewController")
}
コンソールに「show SFSafariViewController」と表示されれば成功です!

SFSafariViewControllerを表示
SFSafariViewController
を表示させる準備が整ったので表示させていきましょう。
とは言っても使い方はとても簡単です。
まずは SafariServices
をimportします。
import SafariServices
これで SFSafariViewController
を使えるので次は表示するまでのコードを見てみましょう。
@IBAction func tappedButton(_ sender: Any) {
// 表示するURLの生成
let url = URL(string: "https://www.google.co.jp/")
// urlを元にSFSafariViewControllerを生成
let safariView = SFSafariViewController(url: url!)
// present関数で表示
present(safariView, animated: true)
}

このようにWebページが表示されれば成功です!
下に全てのコードを載せておきます!
import Foundation
import UIKit
import SafariServices
class SampleSFSafariViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func tappedButton(_ sender: Any) {
let url = URL(string: "https://www.google.co.jp/")
let safariView = SFSafariViewController(url: url!)
present(safariView, animated: true)
}
}
まとめ
SFSafariViewControllerでは簡単にWEBページを表示することができます。
WEBとの連携を必要としない場合には有用ですので理解しておきましょう。