gpt4 book ai didi

swift - swift 中的 WKwebview

转载 作者:行者123 更新时间:2023-11-28 10:39:23 25 4
gpt4 key购买 nike

我在 xib 中有一个 viewController,我以编程方式添加 web View ,我添加了一个背景色来查看,并向 xib 添加了一个 activityIndi​​actor,基本上我想在加载 web View 时显示这个 View 和 activityIndi​​cator,一旦 web View 已完成 我想隐藏 View 并停止 activityIndi​​cator,当我在 web View 中单击任何操作时,然后再次显示 View 并启动 activityLoader。如果我有任何错误,我已将我的代码粘贴到任何建议下方,请随时指导我实现上述场景并帮助我。

运行下面的代码可以看到暗 View ,并且在加载 Web View 时没有加载 activityIndi​​ator。

    //
// CustomWebViewController.swift
// WibmoPay
//
// Created by Hemavathi on 10/07/18.
//

import UIKit
import WebKit

let kJavascriptFileName = "WibmoPayWebKitPostData"

class CustomWebViewController: UIViewController,WKUIDelegate {
@IBOutlet weak var LoadingView: UIView!
var webView: WKWebView!
var merchantDetails: WPMerchantDetails?
var postedParams = false
@IBOutlet weak var loadActivityIndicator: UIActivityIndicatorView!

override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.hidesBackButton = true
self.navigationItem.title = "Pay"
let cancelBarBtn = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(CustomWebViewController.cancelTransaction(_:)))
self.navigationItem.setRightBarButton(cancelBarBtn, animated: true)
self.configureWebView()
}

/*
Dismiss the controller and return from sdk to app
*/
@objc private func cancelTransaction(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}

/*
Injected JavaScript html for showing webview
*/
private func configureWebView(){
let webConfiguration = WKWebViewConfiguration()
self.webView = WKWebView(frame: self.LoadingView.frame,configuration: webConfiguration)
self.LoadingView.addSubview(self.webView)
webView.addSubview(self.loadActivityIndicator)
webView.contentMode = .scaleToFill
//webView.allowsBackForwardNavigationGestures = false
//webView.autoresizesSubviews = true
webView.scrollView.bounces = false
//webView.scrollView.isScrollEnabled = false
//automaticallyAdjustsScrollViewInsets = true
webView.navigationDelegate = self

let frameworkBundle = Bundle(for: WibmoPaySdk.self)
let resourceBundle = Bundle(url: frameworkBundle.url(forResource: "WibmoPay", withExtension: "bundle")!)
let javascriptFilePath = resourceBundle?.path(forResource: kJavascriptFileName, ofType: "html")
let javascriptFileContents = try? String(contentsOfFile: javascriptFilePath!)
self.webView.navigationDelegate = self
self.webView.loadHTMLString(javascriptFileContents!, baseURL: frameworkBundle.bundleURL)
}
}

/*
WKWebView delegates
*/
extension CustomWebViewController : WKNavigationDelegate {

/*
when URL is completed loaded this method is invoked
*/
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if postedParams == false {
self.makePostRequest()
}
self.loadActivityIndicator.stopAnimating()
self.LoadingView.isHidden = false
}

func makePostRequest() {
var url = ""
let postString: [String : String] = [SDKConstant.KEY_REQUEST_PARAM_CHECKSUM : merchantDetails!.generateCheckSumUsingSHA512,
SDKConstant.KEY_REQUEST_PARAM_MERCHANT_NAME : merchantDetails!.merchantName,
SDKConstant.KEY_REQUEST_PARAM_MERCHANT_TXN_ID : merchantDetails!.merchantTxnId,
SDKConstant.KEY_REQUEST_PARAM_MERCHANT_AMOUNT : merchantDetails!.merchantTxnAmount,
SDKConstant.KEY_REQUEST_PARAM_MERCHANT_MESSAGE : merchantDetails!.merchantMessage,
SDKConstant.KEY_REQUEST_PARAM_MERCHANT_PAYMENT_OPTION : merchantDetails!.merchantPaymentOption,
SDKConstant.KEY_REQUEST_PARAM_PAYER_NAME : merchantDetails!.payerName,
SDKConstant.KEY_REQUEST_PARAM_PAYER_MOBILE_NO : merchantDetails!.payerMobile,
SDKConstant.KEY_REQUEST_PARAM_PAYER_EMAIL_ID : merchantDetails!.payerEmailId]

var postParams = ""
for param in postString {
if let urlEncodedValue = param.value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
postParams += "\(param.key):'\(urlEncodedValue)',"
}
}
postParams = String(postParams.dropLast())
if let wibmoPayURL = WibmoPaySdk.sdkManager.wibmoPayUrl{
print("URL:\(String(describing: wibmoPayURL))")
url = "\(wibmoPayURL)\(SDKConstant.API_PAYMENT_URL)"
}else{
WibmoPayError.inCorrectMerchantDetails(missingData: "URL is empty")
}
let jsEvaluator = "post('\(url)',{\(postParams)});"
print(jsEvaluator)
self.webView.evaluateJavaScript(jsEvaluator) { (result, error) in
if let error = error {
print(error)
}
}
postedParams = true

print("webView URL:\(String(describing: webView.url))")
}

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
self.loadActivityIndicator.startAnimating()
self.LoadingView.isHidden = true
print("\(String(describing: webView.url))")
var merchantName: String!
var orderId: String!
var merchantTxnId: String!
var status: String!
var paymentMode: String!
var amount: String!
var commission: String!
var channel: String!

if let redirectedUrl = webView.url, let merchantCbUrl = merchantDetails?.merchantCallbackUrl {
if(redirectedUrl.absoluteString.hasPrefix(merchantCbUrl)) {
print("redirect url matching\(String(describing: redirectedUrl.host))")
if let responseData = redirectedUrl.query {
let params = responseData.components(separatedBy: "&")
for param in params {
let keyValue = param.components(separatedBy: "=")
print("keyValue\(String(describing: keyValue))")

if keyValue.first == "merchant_name"{
merchantName = keyValue.last
print(keyValue , "keyValue.first = \(merchantName)")
continue
} else if keyValue.first == "order_id"{
orderId = keyValue.last
print(keyValue , "keyValue.first = \(orderId)")
continue
} else if keyValue.first == "merchant_txn_id"{
merchantTxnId = keyValue.last
print(keyValue , "keyValue.first = \(merchantTxnId)")
continue
} else if keyValue.first == "status"{
status = keyValue.last
print(keyValue , "keyValue.first = \(status)")
continue
} else if keyValue.first == "payment_mode"{
paymentMode = keyValue.last
print(keyValue , "keyValue.first = \(paymentMode)")
continue
} else if keyValue.first == "amount"{
amount = keyValue.last
print(keyValue , "keyValue.first = \(amount)")
continue
}else if keyValue.first == "commission"{
commission = keyValue.last
print(keyValue , "keyValue.first = \(commission)")
continue
}else if keyValue.first == "channel"{
channel = keyValue.last
print(keyValue , "keyValue.first = \(channel)")
continue
} else {
print("key and value missing")
}
}

let merchantResponse = WibmoPayResponse(merchant_name: merchantName, order_id: orderId, merchant_txn_id: merchantTxnId, status: status, payment_mode: paymentMode, amount: amount, commission: commission, channel: channel)
WibmoPaySdk.sdkManager.transactionCompletionBlock?(merchantResponse,nil)
print("send data success")
self.webView!.stopLoading()
self.dismiss(animated: true, completion: nil)
}
}else{
print("redirectedUrl not matching")
}
}
}

// func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
// self.loadActivityIndicator.stopAnimating()
// }

override var shouldAutorotate: Bool{
return false
}

}

有时我遇到这个错误“无法向服务 com.apple.WebKit.WebContent 发出信号:113:找不到指定的服务”。出现空白屏幕时,我需要强行取消才能完成它。请帮助我解决此错误并实现上述 senario,我们将不胜感激。提前致谢

最佳答案

你可以实现更多的委托(delegate)方法-

func webView(WKWebView,didCommit: WKNavigation!)

当 WebView 开始接收网络内容时调用。

func webView(WKWebView, didReceiveServerRedirectForProvisionalNavigation: WKNavigation!)

当 WebView 接收到服务器时调用。

func webView(WKWebView, didFail: WKNavigation!, withError: Error)

在导航过程中发生错误时调用。

相应地显示和隐藏 View 和事件指示器。

关于swift - swift 中的 WKwebview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51456550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com