//variable declaration
var wkWebView: WKWebView!
let config = WKWebViewConfiguration()
let contentController = WKUserContentController()
var wkWebScriptHandler: WKWebScriptHandler!
let events = [Constant.JavascriptHandler.onLoadEventHandler]
//while loading view first time
override func viewDidLoad() {
super.viewDidLoad()
if let script = generateScript(urlString: Constant.PaperlessXML.paperlessJsURL) {
contentController.addUserScript(script)
}
for event in events {
contentController.add(self, name: event)
}
config.preferences.javaScriptEnabled = true
config.userContentController = contentController
setupWebView(config: config, urlRequest: self.getUrlString(pdfURL: Constant.pdfURL,endPoint: Constant.pdfURLEndPoint).asURLRequest())
}
//Delegate method: this is point where we are injecting javascript
func didSendOtpAndShareCode(_ otpCode: String, _ shareCode: String) {
self.shareCode = shareCode
let json = ["otp":otpCode,"sharecode":shareCode]
self.sendToJavaScript(params: json, comingFrom: "receiveOTP")
}
/// Create custom initializeWkWebView method .
private func setupWebView(config: WKWebViewConfiguration, urlRequest: URLRequest?) {
wkWebView = WKWebView(frame: self.wkwebviewHolder.bounds, configuration: config)
wkWebView.navigationDelegate = self
wkWebView.uiDelegate = self
self.wkwebviewHolder.addSubview(wkWebView)
DispatchQueue.main.async {
if let urlRequest = urlRequest {
self.wkWebView.load(urlRequest)
}
else {
print("not")
}
}
}
private func generateScript(urlString: String) -> WKUserScript? {
var script: WKUserScript?
if let url = URL(string: urlString) {
do {
guard let scriptSource = try? String(contentsOf: url) else { return nil }
script = WKUserScript(source: scriptSource, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
} catch {
print(error)
}
} else {
}
return script
}
/// Create custom getUrlString
private func sendToJavaScript(params: [String:Any],comingFrom: String) {
let jsonString = DigilockerVC.asString(json: params)
switch comingFrom {
case "receiveOTP":
self.evaluteWithJavascriptExpression(jsExpression: "receiveOTP(\(jsonString))")
break
default:
break
}
}
fileprivate func evaluteWithJavascriptExpression(jsExpression: String) {
wkWebView.evaluateJavaScript(jsExpression) { (_, error) in
if error != nil {
print(error?.localizedDescription ?? "")
}
else {
print(error?.localizedDescription ?? "")
}
}
}
// MARK: - WKNavigationDelegate
extension AdharDetailVC: WKScriptMessageHandler, WKNavigationDelegate, WKUIDelegate {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
switch message.name {
case Constant.JavascriptHandler.onLoadEventHandler:
guard let jsonString = message.body as? String else {return}
if let jsonObject = Utility.convertToDictionary(jsonString: jsonString) {
self.paperlessModel = PaperlessModel(json: jsonObject)
}
break
default:
break
}
}
}
ПРИМЕЧАНИЕ. Приведенный выше код работает нормально на iOS симуляторе
Я пробовал:
Xcode: 11,3, 11,4 бета
iOS : 13.2, 13.3, 13.4 бета
Проблема : при запуске вышеуказанного кода на устройстве iPhone (iOS 13.2, 13.3, 13.4 бета) содержимое загружается нормально, но после внедрения javascript на страницу, нет ответа от javascript стороны. Если кто-то получил эту проблему, пожалуйста, помогите мне.
Я искал эту проблему в нескольких местах, но не нашел решения или причина.