SwiftUI - iOS 13 UIViewRepresentable of WKWebView gets Thread 1: EXC_BREAKPOINT crash

佐手、 提交于 2021-02-07 19:27:38

问题


I'm trying to port WKWebView over to SwiftUI. Here's my code:

import SwiftUI
import WebKit

struct ContentView: View {
    var body: some View {
        WebViewWrapper()
    }
}

/**
 WKWebView ported over to SwiftUI with `UIViewRepresentable`.
 */
final class WebViewWrapper: UIViewRepresentable {
    
    /// `UIViewRepresentable` required function #1.
    func makeUIView(context: Context) -> WKWebView  {
        print("make")
        let webView = WKWebView() /// EXC_BREAKPOINT error here
        return webView
    }
      
    /// `UIViewRepresentable` required function #2
    func updateUIView(_ uiView: WKWebView, context: Context) {
    }
}

That's it. I created a new SwiftUI project and pasted it in. However, I get this error:

Thread 1: EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0)

... with nothing printed in the console. This happened for both iOS 13.0 and iOS 13.1.

But, on iOS 14.2, it works fine. The crash also seems to happen only for WKWebView. For example, if I replace it with UITextView, it runs without problems.

import SwiftUI
import WebKit

struct ContentView: View {
    var body: some View {
        TextViewWrapper()
    }
}

/**
 UITextView ported over to SwiftUI with `UIViewRepresentable`.
 */
final class TextViewWrapper: UIViewRepresentable {
    
    /// `UIViewRepresentable` required function #1.
    func makeUIView(context: Context) -> UITextView  {
        print("make")
        let textView = UITextView() /// no error, works fine
        return textView
    }
      
    /// `UIViewRepresentable` required function #2
    func updateUIView(_ uiView: UITextView, context: Context) {
    }
}

I'm running Big Sur 11.0.1 on an M1 Mac, but I don't think that should be a problem. My Xcode version is 12.2 (12B45b).

Edit: Big Sur / M1 might be the problem.

I just ran it on the same version of Xcode on my Intel Mac, Catalina 10.15.5, and it works fine.


回答1:


The problem is due to a combination of running on an M1 Mac and using an iOS version prior to 14. The problem is known to Apple.




回答2:


Your UIViewRepresentable should be a struct not a class

struct WebViewWrapper: UIViewRepresentable {
^^^^^^



回答3:


As not reproducible, just guessing... try different constructors, like

let wkWebConfiguration = WKWebViewConfiguration()
let webView = WKWebView(frame: .zero, configuration: wkWebConfiguration)

or even with some defined frame (anyway it does not matter later for SwiftUI view hierarchy)

let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 100, height: 100), 
                        configuration: wkWebConfiguration)


来源:https://stackoverflow.com/questions/65224739/swiftui-ios-13-uiviewrepresentable-of-wkwebview-gets-thread-1-exc-breakpoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!