iosswiftwebviewios-web-app

Simplest webview app in iOS - fail to run


I am trying to make an ios app that simply open a URL. So basically a webview app. I am using XCode 12.4 and that's what I did:

  1. Create new project->iOS App --> (see image below)
  2. Create a new file: ViewController.swift -->
import WebKit
class WebViewController: UIViewController, WKNavigationDelegate {

    var webView: WKWebView!
    
    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let url = URL(string: "https://developer.apple.com")!
        webView.load(URLRequest(url: url))
    }
}
  1. Build and Run.

The issue is that the app continues to open on "Hello World" and I imagine the reason is that the MyappApp.swift file is calling ContentView instead of ViewController

import SwiftUI

@main
struct myappApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

How can I fix this?

Disclaimer: This is my first iOS app and I know little to nothing about iOS dev.

enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here


Solution

  • You are very close... Wrap your WebViewController in a UIViewControllerRepresentable to make it compatible with SwiftUI

    import SwiftUI
    struct WebView_UI: UIViewControllerRepresentable {
        func makeUIViewController(context: Context) -> some UIViewController {
            let vc = WebViewController()
            return vc
        }
        func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
            
        }
    }
    

    And then reference your new SwiftUI UIViewControllerRepresentable in a SwiftUI struct. For example...

    struct myappApp: App {
        var body: some Scene {
            WindowGroup {
                WebView_UI()
            }
        }
    }
    

    Or...

    struct ContentView: View {
        var body: some View {
            VStack{
                Text("Hello World!").padding()
                WebView_UI()
            }
        }
    }