Memory leak occurs when using WKWebView in swiftui

Viewed 100

While learning to use webview in my app I just added a webview and detected a memory leak.

I found a lot of demos on the Internet and tested them and all have this problem.

Here is my test code:

Instruments screenshot

import SwiftUI
import WebKit

struct SWKWebView: UIViewRepresentable {
    
    @Binding var url: String?
    
    func makeUIView(context: Context) -> WKWebView {
        let webview = WKWebView()
        webview.navigationDelegate = context.coordinator
        return webview
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        if let url = url, let requetURL = URL(string: url)  {
            uiView.load(URLRequest(url: requetURL))
        }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator()
    }
        
    class Coordinator: NSObject,WKNavigationDelegate {
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            webView.evaluateJavaScript("document.title") { (result, error) in
                print("didFinish:\(String(describing: result ?? ""))")
            }
        }
    }
}

struct TTTest: View {
    @State var url: String? = "https://www.google.com"

    var body: some View {
           SWKWebView(url: $url)
       }
}
1 Answers

When I updated the IOS system to version 15.5, this problem was solved

Related