LoginSignup
2
2

More than 5 years have passed since last update.

iOSシミュレータでWebサイトが開けないとき

Posted at

 表題なのですが、まぁ丸一日分時間をかけてしまったのでメモを残しておきます。

iOSアプリからWebサイトを開こう

 と思いました。参考にしてる本にもちゃちゃっと書いてありましたし、余裕でいけると思ってコードを書いて、どれどれ、と実行。(サイトとかは本当はDBに保存されてるのを取ってきたりしてるんですが適当に変えてます)

ViewController.swift

    @IBAction func wakeWebsite(_ sender: Any) {
        // urlの設定
        let url = URL(string: "https://ja.wikipedia.org/wiki/1月1日".addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!)!
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url)
        }
    }

ドメインが表示されて、いけるかな、と思ったら。

”Safari cannot open the page because it could not establish a secure connection to the server."

おおっと。ページが表示されず、エラーメッセージが表示されてます。

迷走

  • ATSでホワイトリストの設定(そもそもHTTPSじゃん!)
  • %エンコードはしてる、よなぁ
  • 違うページ開いてみる。
     これは、yahooやgoogleだとまた別のメッセージがでて、ぽちぽちと押してると表示出来るようになることはなる
  • 違うやり方でやってみる
  • シンプルにプロジェクトを作り直して試す

違うやり方〜WkWebView

WKWebViewで表示してみるかー

ViewController.swift

import WebKit

~~
    @IBOutlet weak var webView: WKWebView!

    override func viewDidLoad(){
        super.viewDidLoad()
        // URLRequestを作る
        let urlRequest = URLRequest(url: URL(string: "https://ja.wikipedia.org/wiki/1月1日".addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!)!)
        webView.load(urlRequest)
    }

Storyboardで配置してOutlet接続してます。
結果はページまっしろ。

実際にはUrlに変換した段階で、デバッガで内容を見るとSafariでちゃんとページ表示してくれてるんですよね。

違うやり方〜SFSafariViewController

ViewController.swift

import SafariServices

    @IBAction func wakeWebsite(_ sender: Any) {
        // urlの設定
        let url = URL(string: "https://ja.wikipedia.org/wiki/1月1日".addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!)!
        // safariで起動
        let svc = SFSafariViewController(url: url)
        present(svc, animated: true, completion: nil)
    }

これも最初のURLスキーム形式と同じ結果。

解決方法

…とても単純でした。Macに入っているウイルスセキュリティのWebシールドをオフにすること。ブロックされてしまって表示されてないだけでした。
WkWebViewのは試しませんでしたが、他の2つはどっちもちゃんと動きました。

参考
https://stackoverflow.com/questions/46980164/cant-visit-website-on-ios-simulator-this-connection-is-not-private

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2