10
Help us understand the problem. What are the problem?

posted at

updated at

[Swift] アプリ内でSafariを開く方法

たまに使うときに忘れてるので備忘録です。

完成形

.pageSheet
(iOS13以降でデフォルトの画面遷移)
.fullScreen .overFullScreen
pageSheet.gif fullScreen.gif ezgif.com-gif-maker.gif

|

コード

import SafariServicesを忘れずに。

ViewController.swift
import SafariServices

デフォルト(.pageSheet

ViewController.swift
let webPage = "https://google.com"
let safariVC = SFSafariViewController(url: NSURL(string: webPage)! as URL)
// pageSheetの場合は、modalPresentationStyleの部分を書かなくてもpageSheetで表示されます。
safariVC.modalPresentationStyle = .pageSheet
present(safariVC, animated: true, completion: nil)

.fullScreen

ViewController.swift
safariVC.modalPresentationStyle = .fullScreen

.overFullScreen

ViewController.swift
safariVC.modalPresentationStyle = .overFullScreen

使用例

@IBAction func TappedWebBtn(_ sender:UIButton) {
    let webPage = "https://google.com"
    let safariVC = SFSafariViewController(url: NSURL(string: webPage)! as URL)
    safariVC.modalPresentationStyle = .pageSheet
    present(safariVC, animated: true, completion: nil)
}

他の遷移アニメーション

.formSheet .currentContext .overCurrentContext .popover .blurOverFullScreen
他のアニメーションも実装方法は同じなので、公式ドキュメントをご確認ください。
https://developer.apple.com/documentation/uikit/uimodalpresentationstyle

サンプル

サンプルコードはGitHubにあげてあります。
https://github.com/rea-sna/SafariSample

最後に

最後までご覧いただきありがとうございました。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
10
Help us understand the problem. What are the problem?