前提・実現したいこと
Swiftでゲーム用のブラウザを作っています。
WKWebViewよりオフライン時にエラーを取得してSafariのようにエラー表示したい。
発生している問題・エラーメッセージ
Safariのオフラインのような機能を実装しようとしてますが、エラー取得や表示方法がわかりません。
該当のソースコード
ViewController.swift
import Cocoa import WebKit class ViewController: NSViewController { @IBOutlet weak var WebView: WKWebView! var cookies = Dictionary<String,String>() var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() let url = "https://google.com" var request = URLRequest(url: URL(string: url)!) var httpcookies = [HTTPCookie]() for (key, value) in cookies { httpcookies.append(ViewController.makeCookie(key: key, value: value)) } let headers = HTTPCookie.requestHeaderFields(with: httpcookies) for (name, value) in headers { request.addValue(value, forHTTPHeaderField: name) print("Made HTTPCookie") } WebView.load(request) // Do any additional setup after loading the view. } class func makeCookie(key:String, value:String) -> HTTPCookie{ let cookies = HTTPCookie(properties: [ .domain: "google.com", .path: "/", .name: key, .value: value, .secure: "FALSE", .expires: NSDate(timeIntervalSinceNow: 31556926) ])! return cookies } func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { guard let url = navigationAction.request.url else { return nil } guard let targetFrame = navigationAction.targetFrame, targetFrame.isMainFrame else { webView.load(URLRequest(url: url)) return nil } return nil } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } }
AppDelegate.swift
import Cocoa import WebKit @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { let e = error as NSError if e.code == -1009 { print("NotConnectedToInternet") } } func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
試したこと
以下のページでiOSの内容だが取得方法を調べた。
http://harumi.sakura.ne.jp/wordpress/2019/03/04/wkwebviewでインターネット接続エラーを取得する/
https://qiita.com/aryzae/items/9b3d6f77cb5082665220
補足情報(FW/ツールのバージョンなど)
Xcode 11.0 (11A420a)
Xcode Version 11.1 (11A1027)
MacOS Mojave 10.14.6(18G103)
あなたの回答
tips
プレビュー