Я загрузил форму iframe в wkwebview и она работает нормально. Если нажать кнопку сканера внутри фрейма и открыть камеру для сканирования документа, после загрузки документа на сервер он вернется в режим просмотра 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()
}
Моя проблема, когда я возвращаюсь к представлению wkweb после того, как из SDK сканера отображается пустой белый экран. Как обновить sh экран, когда я возвращаюсь к просмотру веб-страниц каждый раз, когда сканер SDK закрывается?
Любая помощь очень ценится, пожалуйста ...