从 iOS Swift 中的 cam 扫描仪 SDK 返回时,WKwebview 是空白屏幕?

Posted

技术标签:

【中文标题】从 iOS Swift 中的 cam 扫描仪 SDK 返回时,WKwebview 是空白屏幕?【英文标题】:WKwebview is blank white screen when returning from cam scanner SDK in iOS Swift? 【发布时间】:2020-01-22 17:49:27 【问题描述】:

我已将 iframe 表单加载到 wkwebview 中,并且工作正常。当点击 iframe 内的扫描仪按钮并打开相机扫描文档时,文档上传到服务器后,它将返回 wkweb 视图,但此处 wkweb 视图未刷新并显示空白屏幕。

这是我的 wkweb 视图代码:

    private func loadWebView()

    webView.uiDelegate = self
    webView.allowsBackForwardNavigationGestures = true

         do 
             guard let filePath = Bundle.main.path(forResource: "index", ofType: "html")
                 else 
                     // File Error
                     print ("File reading error")
                     return
             

             let contents =  try String(contentsOfFile: filePath, encoding: .utf8)
             let baseUrl = URL(fileURLWithPath: "https://url")
            DispatchQueue.main.async 

                self.webView.loadHTMLString(contents as String, baseURL: baseUrl)

            

         
         catch 
             print ("File HTML error")
         




    webView.configuration.preferences.javascriptEnabled = true
    webView.configuration.userContentController.add(self, name: "jsHandler")
    webView.configuration.userContentController.add(self, name: "saveHandler")
    webView.configuration.userContentController.add(self, name: "openCamera")




func makeSaveForm(ProcessInstanceId: String, FullFormKey: String, TaskIdValue: String, FormValues: String) -> saveFormModel 

        let newForm = saveFormModel()
        newForm.ProcessInstanceId = ProcessInstanceId
        newForm.FullFormKey = FullFormKey
        newForm.TaskIdValue = TaskIdValue
        newForm.FormValues = FormValues

        return newForm

  


func ProcessInstanceIDApiCall(ProcessInstId: String)

        let authToken = UserDefaults.standard.string(forKey: "authToken")
        print("id for process instance", ProcessInstId)
                          let bearerToken: String = "Bearer " + (authToken ?? "")
                          print("baearer token::\(bearerToken)")

        let headers:HTTPHeaders = ["Content-Type":"Application/json",
                                  "Authorization": "Bearer " + (authToken ?? ""),
                                  "Accept":"application/json"]

    AF.request("https://api url/process-instance/\(ProcessInstId)/variables", method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).responseJSON  (response:AFDataResponse<Any>) in


        print("process instance id api",response.result)

        switch response.result 
            case .success:

                print("instance response", response.value )
                guard let data = response.value  else 
//                       print("request failed \(error)")

                           return
                   

                self.anyValueJson = response.value



                self.jsonStringProcessInstanceID = self.JSONStringify(value: data as AnyObject)



                print("raw response: \(String(describing: self.jsonStringProcessInstanceID))")



                case .failure(let error):
                    print("Error:", error)
                

        



    //api call end

public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) 

    if message.name == "jsHandler" 
       //  print(message.body)

     else if message.name == "saveHandler" 

        let values = message.body
        print(values)
        let jsonString = JSONStringify(value: values as AnyObject)
        print(jsonString)

        formValues = jsonString

        let newSaveForm = self.makeSaveForm(ProcessInstanceId:  self.processInstanceId ?? "", FullFormKey: self.fullFormKey ?? "", TaskIdValue: self.taskIdValue ?? "", FormValues: jsonString )

        //realm create/update saveform based task id
        let realm = try! Realm()
        if realm.object(ofType: saveFormModel.self, forPrimaryKey: newSaveForm.TaskIdValue) != nil 
            try! realm.write 
                print("already exist")
                //.all is equivalent to true and .error is equivalent to false
                realm.add(newSaveForm, update: .all)

            
         else 
            try! realm.write 
                print("new document written")
                realm.add(newSaveForm) //RLMException occurs here
            
        

     else if message.name == "openCamera" 

      print("open camera",message.body)

        let base64Encoded = message.body
        let jsonString = JSONStringify(value: base64Encoded as AnyObject)

       do
            if let json = jsonString.data(using: String.Encoding.utf8)
                if let jsonData = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as? [String:AnyObject]

                    let id = jsonData["scannerData"] as! String
                    print("scanner data ::", id)

                    let vc1 =  ScannerViewController()

                    let v = vc1.scanParameters(scannerDataBase64: id)

                    print("v", v)

                    let newVC = A8Scan(self)
                    newVC.showScanner()



                
            
        catch 
            print(error.localizedDescription)

        


   func loadFormView()

      let setPath = "https://api url/\(formKey ?? "")/index.html";
            let js = "setFrame('" + setPath + "')";
            print("js::\(js)")

            webView.evaluateJavaScript(js)  (r, error) in

                if error == nil 

                    DispatchQueue.main.asyncAfter(deadline: .now() + 2.0)

                        print(r ?? "empty")

                        let realm = try! Realm()
                        let object = realm.object(ofType: saveFormModel.self, forPrimaryKey: self.taskIdValue)
                        print("object", object ?? "")



                        print("json api string", self.jsonStringProcessInstanceID ?? "")

                        let authValue =  "Bearer  \(self.authTokenValue ?? "")"

                        if object?.FullFormKey != nil 
                               if let jsonStr = self.jsonStringProcessInstanceID 
                            let l = "loadform('\(object?.FullFormKey ?? "")', '\(authValue)', '\(object?.ProcessInstanceId ?? "")', \(object?.FormValues ?? ""), \(jsonStr))"
                            self.webView.evaluateJavaScript(l, completionHandler: nil)
                            

                         else 

                            if let jsonStr = self.jsonStringProcessInstanceID 

                                print("json str::::", jsonStr)

                                let l = "loadform('\(self.fullFormKey ?? "")', '\( authValue)', '\(self.processInstanceId ?? "")', \(jsonStr))"
                                self.webView.evaluateJavaScript(l, completionHandler: nil)
                            


                        



                        self.tapCallback = 

                            print("tap called save")
    //                        let s = "submitEvent('\(self.saveArg)')"
                                let save = "submitEvent('save');"

                            self.webView.evaluateJavaScript(save, completionHandler: nil)

                        

                    
                 else 

                    print("web view didfinish loading error",error)
                

            



   public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) 

       print("Web View didFinish Loading");
    loadFormView()




   

当我从扫描仪 SDK 返回 wkweb 视图时出现问题,它显示空白屏幕。每次扫描仪 SDK 关闭时返回 Web 视图时如何刷新屏幕?

任何帮助非常感谢,请...

【问题讨论】:

webView.opaque = false 【参考方案1】:

问题是由 AVG AntiVirus 的网络防护造成的。出于某种原因,AVG webshield 将来自模拟器的所有网络通信视为欺诈。 以下屏幕截图显示了在模拟器上运行的 Safari 应用程序。它说 www.apple.com 或任何其他网站都不安全。

以下屏幕截图来自 system.log,显示了 webkit 的错误。

您可以通过安装 AVG 防病毒软件并打开 webshield 来重现此问题。您的应用程序(在模拟器上)中的 WKWebview 不会加载任何内容。

taken from here

【讨论】:

以上是关于从 iOS Swift 中的 cam 扫描仪 SDK 返回时,WKwebview 是空白屏幕?的主要内容,如果未能解决你的问题,请参考以下文章

在 Swift 中从 WebView 打开条码扫描器

Metal(iOS)中的多重采样/锯齿状边缘

uboot下 EMMC和SD卡操作命令

Swift:为啥我的 iOS 不能扫描其他蓝牙设备

如何在 iOS、Swift 中搜索 iBeacons UUID,并扫描周围的所有 iBeacons

ESP32CAM-Micropython-web视频