简体   繁体   中英

WKwebview is blank white screen when returning from cam scanner SDK in iOS Swift?

I have loaded iframe form into wkwebview and its working fine. When the tap scanner button inside an iframe and it opens the camera to scan the document, after document uploaded to the server it will return to wkweb view but here wkweb view is not refreshed and showing a blank white screen.

Here is my code for wkweb view:

    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()




   }

My issue when I'm returning to wkweb view after from scanner SDK it shows a blank white screen. How to refresh the screen when I return to the web view each time scanner SDK close?

Any help much appreciated, please...

The problem is being caused by AVG AntiVirus's webshield. For some reason AVG webshield treats all network communication from the simulator as fraudulent. The following screenshot shows the safari app running on simulator. It says that www.apple.com is not safe or any other website.

Safari 截图

The following screenshot is from system.log showing errors with webkit.

系统日志

You can replicate this problem by installing AVG antivirus and turning on the webshield. WKWebview in your App(On the simulator) wouldn't load anything.

taken from here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM