📱

【Swift】【iPhone】アプリからWebを表示するサンプルコード

2024/02/12に公開

外部ブラウザでWebページを表示

ViewController.swift
    @IBAction func showBrowser(_ sender: Any) {
        let application = UIApplication.shared
        application.open(URL(string: "https://www.google.com/")!)
    }

WebViewでWebページを表示

WebViewController.swift
import UIKit
import WebKit

class WebViewController: UIViewController , WKUIDelegate{
    
    var webView: WKWebView!
    
    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let myURL = URL(string:"https://www.google.com/")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }
}

Discussion