-1

This is a web browser i'm building for macOS and I'm trying to access a string variable inside my content view. But i'm getting this error

Cannot use instance member 'site' within property initializer; property initializers run before 'self' is available

defining webView inside the body works but my refresh page function in the button stops working.

struct ContentView: View {
    @State private var site: String = "www.google.com/"
    let webView = WebView(request: URLRequest(url: URL(string:"https://" + site)!))
     
    
    
    var body: some View {
     
      TextField("Enter a URL", text: $site) //This is the address bar
        
        NavigationView{
          //  let webView = WebView(request: URLRequest(url: URL(string: "https://" + site )!))
                   
        webView
            .frame(width: 860, height: 860, alignment: .center)
            
        Button(action: {
            self.webView.refresh()
            }) {
                Text("Refresh Page")
            }
        }
    }
}

WebView

import SwiftUI
import WebKit
import AppKit

struct WebView: NSViewRepresentable {
    let request: URLRequest
    private var webView: WKWebView?
    
    init (request: URLRequest) {
        self.webView = WKWebView()
        self.request = request
    }
        
    
    func makeNSView(context: Context) -> WKWebView {
        return webView!
    }
 
    
    
    func refresh(){
       webView?.reload()
       
    }
    
    
    func updateNSView(_ nsView: WKWebView, context: Context) {
        nsView.load(request)
    }
    
    
}
1

1 Answer 1

1

Use computed property.

var webView: WebView {
        return WebView(request: URLRequest(url: URL(string:"https://" + self.site)!))
}
Sign up to request clarification or add additional context in comments.

3 Comments

it's able to build successfully but the app window now doesn't show. Getting Thread 1 breakpoint highlights in code
@dreambug I posted ans after I successfully run in my demo. Please this is something different from your side.
and its just debug breakpoint just play

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.