0

I have added a WKwebview in SwiftUI via UIVewRepresentable. I am having difficulties getting some buttons to make the web view go back and go forward. Below is the two classes I have made but I am not even getting print to work ( maybe a bug? ).

import SwiftUI

import WebKit

struct Webview : UIViewRepresentable {

let request: URLRequest

func makeUIView(context: Context) -> WKWebView  {
    return WKWebView()
}

func updateUIView(_ uiView: WKWebView, context: Context) {
    uiView.load(request)
}

func goBack(){
    // go back
    print("go back")
}

func goForward (){
    // go forward
    print("go forward")
}
}



import SwiftUI

struct FullWebView : View {

let webview = Webview(request: URLRequest(url: URL(string: "https://www.apple.com")!))

var body: some View {
    VStack{
        HStack{
            Button(action: {
                //do something
                self.webview.goBack()
            }){
                Text("back")
            }

            Spacer()

            Button(action: {
                //do something
                self.webview.goForward()
            }){
                Text("forward")
            }

        }

        webview
    }
}
}
11
  • Is your specific issue getting a console verification to go back or forward, or is it with getting the WKWebView to do it? More, where are you trying to actually navigate backward/forward? I'd expect it's in UIKit, right?
    – user7014451
    Jun 25, 2019 at 20:43
  • I realised that the print method don’t work in preview only the simulator, but I still can’t work out a way to get my web view to goback Jun 25, 2019 at 20:52
  • I don't use WKWebView, but I'd assume web navigation needs to somehow use it, right? i'm using a MTKView and it's delegates in SwiftUI to update it's draw method. Are we talking something similar? Are you trying to kick off something inside WKWebView through its representative?
    – user7014451
    Jun 25, 2019 at 20:55
  • Look at the accepted answer to this question - hopefully it will get you going. stackoverflow.com/questions/56584059/…
    – user7014451
    Jun 25, 2019 at 20:57
  • I’ve never used MTKView I’m afraid, so I’m not sure about that, WKWebview has methods goBack() to go back a page and goForward() to go forward a page. There is no WKWebview delegate. Im thinking I need to use context somehow?? Jun 25, 2019 at 20:59

2 Answers 2

4

dfd thank you for pointing me on the correct path, your answer needed a little modification because adding the webview as a var to the struct means I needed to set a value on it when I use it, so I also had to add a custom init method. Anyway here is the code that works.

Webview struct

import SwiftUI

import WebKit

struct Webview : UIViewRepresentable {


    let request: URLRequest
    var webview: WKWebView?

    init(web: WKWebView?, req: URLRequest) {
        self.webview = WKWebView()
        self.request = req
    }

    func makeUIView(context: Context) -> WKWebView  {
        return webview!
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.load(request)
    }

    func goBack(){
        webview?.goBack()
    }

    func goForward(){
        webview?.goForward()
    }
  }

and here is the struct using the webview and adding the buttons to the top

import SwiftUI

struct FullWebView : View {


let webview = Webview(web: nil, req: URLRequest(url: URL(string: "https://www.apple.com")!))

var body: some View {
    VStack{
        HStack{
            Button(action: {
                //do something
                self.webview.goBack()
            }){
                Text("back")
            }

            Spacer()

            Button(action: {
                //do something
                self.webview.goForward()
            }){
                Text("forward")
            }

        }

        webview
    }
}
}
1
  • 1
    I'll delete my answer - glad it got you pointed the right way.
    – user7014451
    Jun 26, 2019 at 21:44
0

Here is another way using Combine

import Combine
import SwiftUI
import WebKit

private struct WebView: UIViewRepresentable {
    enum Action {
        case goBack, goForward
    }
    
    let htmlContent: String
    let actionPublisher: any Publisher<Action, Never>
    
    func makeUIView(context: Context) -> WKWebView {
        let view = WKWebView()
        context.coordinator.cancellable = actionPublisher.sink { action in
            view.stopLoading()
            switch action {
            case .goBack:
                if view.canGoBack {
                    view.goBack()
                }
            case .goForward:
                if view.canGoForward {
                    view.goForward()
                }
            }
        }
        loadContent(in: view)
        return view
    }
    
    func updateUIView(_ view: WKWebView, context: Context) {
        
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator()
    }
    
    private func loadContent(in view: WKWebView) {
        if let url = URL(string: htmlContent), url.scheme == "https" {
            let req = URLRequest(url: url)
            view.load(req)
        }
    }
    
    class Coordinator: NSObject {
        var cancellable: AnyCancellable?
    }
}

struct FullWebView: View {
    let url: String
    private let actionPublisher = PassthroughSubject<WebView.Action, Never>()   
 
    var body: some View {
        VStack {
            WebView(htmlContent: url, actionPublisher: actionPublisher)
            HStack {
                Button {
                    actionPublisher.send(.goBack)
                } label: {
                    Image(systemName: "arrow.left")
                }
                Spacer()
                Button {
                    actionPublisher.send(.goForward)
                } label: {
                    Image(systemName: "arrow.right")
                }
            }
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.