您现在的位置是:主页 > news > 什么样式表一般用于大型网站/白度指数

什么样式表一般用于大型网站/白度指数

admin2025/5/2 19:00:07news

简介什么样式表一般用于大型网站,白度指数,网站视频提取软件app,怎样注册网站中文域名本文通过一个实例介绍了几种App与Web交互的情形: 1.同步返回参数给Web. 比如App提供方法返回token, Web中在需要的时候即时拿取. 2.Web异步调用App提供的方法. 使用这种方式,结合JS提供给App调用的方法,页可以给Web返回参数,不过这种方式是异步. 3.App中调用JS提供的方法. 例: …

什么样式表一般用于大型网站,白度指数,网站视频提取软件app,怎样注册网站中文域名本文通过一个实例介绍了几种App与Web交互的情形: 1.同步返回参数给Web. 比如App提供方法返回token, Web中在需要的时候即时拿取. 2.Web异步调用App提供的方法. 使用这种方式,结合JS提供给App调用的方法,页可以给Web返回参数,不过这种方式是异步. 3.App中调用JS提供的方法. 例: …

本文通过一个实例介绍了几种App与Web交互的情形:

1.同步返回参数给Web. 比如App提供方法返回token, Web中在需要的时候即时拿取.
2.Web异步调用App提供的方法. 使用这种方式,结合JS提供给App调用的方法,页可以给Web返回参数,不过这种方式是异步.
3.App中调用JS提供的方法.

例:

import UIKit
import WebKitclass WKWebVC: UIViewController {var webView: BaseWebView!var configuration: WKWebViewConfiguration!/// 进度条private lazy var progressView: UIProgressView = {let p = UIProgressView()p.tintColor = .redp.trackTintColor = .grayreturn p}()/// 打开链接private var openUrl: String = "" {didSet {if (Tools.verifyURL(urlString: openUrl) == false) {openUrl = openUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!}}}/// 缓存策略private var webCachePolicy: NSURLRequest.CachePolicy?deinit {webView.removeObserver(self, forKeyPath: "estimatedProgress")webView.configuration.userContentController.removeScriptMessageHandler(forName: "callHandler")}override func viewDidLoad() {super.viewDidLoad()setupUI()}private func setupUI() {// 配置configuration = WKWebViewConfiguration()configuration.allowsInlineMediaPlayback = truelet preferences = WKPreferences()preferences.javaScriptEnabled = truepreferences.javaScriptCanOpenWindowsAutomatically = truepreferences.setValue(true, forKey: "allowFileAccessFromFileURLs")configuration.preferences = preferenceslet pool = WKProcessPool()configuration.processPool = poolconfiguration.userContentController = WKUserContentController()configuration.userContentController.add(self, name: "callHandler")// 初始化webView = BaseWebView(frame: .zero, configuration: configuration)webView.navigationDelegate = selfwebView.uiDelegate = selfwebView.allowsBackForwardNavigationGestures = truewebView.isOpaque = falseview.addSubview(webView)webView.snp.makeConstraints { (make) inmake.top.equalToSuperview().offset(topOffset)make.left.right.bottom.equalToSuperview()}// 进度webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)view.addSubview(progressView)progressView.snp.makeConstraints { (make) inmake.top.equalToSuperview().offset(topOffset)make.left.right.equalToSuperview()make.height.equalTo(2)}// 加载guard let url = URL(string: openUrl) else {return}if let tempPolicy = webCachePolicy {webView.load(URLRequest(url: url, cachePolicy: tempPolicy, timeoutInterval: 15))} else {webView.load(URLRequest(url: url))}}}extension WKWebVC {/// 监听加载进度override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {guard let obj = object as? WKWebView, let key = keyPath, let dict = change else {super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)return}if obj == webView && key == "estimatedProgress" {let progress = dict[.newKey] as! NSNumberprogressView.alpha = 1.0progressView.setProgress(progress.floatValue, animated: true)if progress.floatValue >= 1.0 {UIView.animate(withDuration: 0.3, delay: 0.3, options: .curveEaseOut, animations: {self.progressView.alpha = 0.0}) { (_) inself.progressView.setProgress(0, animated: true)}}} else {super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)}}
}extension WKWebVC : WKNavigationDelegate {func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {debugPrint("加载成功")}func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {debugPrint("加载失败")}
}extension WKWebVC : WKScriptMessageHandler {/**@abstract 同步返回数据给web@param prompt: 这里用来传方法名称(字符串)@param defaultText: 这里用来传参数(字符串或json字符串)@discussion JS部分在需要跟原生交互的地方写后面的方法 window.prompt(text,defaultText);@link https://www.jianshu.com/p/c89951c4f5b0*/func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {if prompt == "getToken" {let token : String = AppUserDefaults.shared.token ?? ""completionHandler(token)} else if prompt == "statusBarHeight" {let barHeight = UIDevice.statusBarHeight()let str = String(format: "%.0f", barHeight)completionHandler(str)} else if prompt == "safeAreaBottom" {let botHeight = UIDevice.safeAreaBottom()let str = String(format: "%.0f", botHeight)completionHandler(str)}}/**@abstract 异步 web调取app的方法@discussion JS部分在需要跟原生交互的地方调用方法: window.webkit.messageHandlers.<方法名>.postMessage(<数据>)*/func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {// 判断是否Messagehandlerlet funcName = message.name// 拿到方法名guard let body = message.body as? String else {return}let dict = Tools.getDictionaryFromJSONString(jsonString: body)if funcName == "callHandler" {// 获取方法/操作和参数let method = dict["method"] as? String ?? ""let params = dict["params"]switch method {case "pay":pay(data: params)case "goback":gobackAction()case "goAppInterface":self.goAppInterface(params: params)case "callPhone":Tools.callPhone(params: params)default:break}}}/// 返回func gobackAction() {if webView.canGoBack {guard let url = webView.url?.absoluteString else {webView.goBack()return}if !url.starts(with: "http://XXX") {webView.goBack()return}}self.popVC()self.dismiss(animated: true, completion: nil)self.webView.configuration.userContentController.removeScriptMessageHandler(forName: "callHandler")}/**@abstract 跳转到app中的页面@param params: home-首页 search-搜索 cart-购物车 footprint-足迹*/func goAppInterface(params:Any?) {if let obj = params, let mark = obj as? String {if mark == "home" {} else if mark == "search" {} else if mark == "cart" {} else if mark == "footprint" {} else if mark == "login" {}}}/// 支付private func pay(data: Any?) {guard let params = data as? [String:Any] else {return}guard let payInfo = params["payInfo"] as? [String:Any] else {return}let json = JSON(payInfo)let payModel = PayModel.parseObject(json: json)// 支付结果NotificationCenter.default.addObserver(self, selector: #selector(payResult(_:)), name: NSNotification.Name("payResult"), object: nil)if payModel.alipay_sdk?.length != 0 {AlipaySDK.defaultService()?.payOrder(payModel.alipay_sdk, fromScheme: "JXF", callback: { (result) indebugPrint("result = \(String(describing: result))")})} else {let req = PayReq()req.partnerId = payModel.partneridreq.prepayId = payModel.prepayidreq.nonceStr = payModel.noncestrreq.timeStamp = UInt32(payModel.timestamp)req.package = payModel.packagereq.sign = payModel.signWXApi.send(req) { (result) indebugPrint("---\(result)")}}}/// 支付结果@objc func payResult(_ notifi: Notification) {let result = notifi.userInfo as! [String: Any]let code = result["code"] as! Intswitch code {case 1:AlertHUD.showMsg("支付成功")breakdefault:AlertHUD.showMsg("支付失败")break}let js = String(format: "payResponse('%d');", code)self.webView.evaluateJavaScript(js) { (data, error) inprint(error?.localizedDescription ?? "oc调取js成功")}NotificationCenter.default.removeObserver(self, name: NSNotification.Name("payResult"), object: nil)}}

支付成功回调:

extension AppDelegate {func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {if url.host == "safepay" {AlipaySDK.defaultService()?.processOrder(withPaymentResult: url, standbyCallback: { (response) inlet res = response as! [String : Any]let code = res["resultStatus"] as! Stringvar result: [String: Any] = [:]result["code"] = (code == "9000") ? 1 : 0NotificationCenter.default.post(name: NSNotification.Name("payResult"), object: nil, userInfo: result)})return true}return true}}

WKWebView实现“全屏”展示:

import Foundation
import WebKitclass BaseWebView: WKWebView {override var safeAreaInsets: UIEdgeInsets {return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)}}
import Foundation
import UIKitstruct Tools {/// 验证URL的有效性static func verifyURL(urlString: String?) -> Bool {if let urlString = urlString {if let url = NSURL(string: urlString) {return UIApplication.shared.canOpenURL(url as URL)}}return false}/// 拨打电话static func callPhone(params:Any?) {if let obj = params, let phone = obj as? String {if isBlank(phone) {return}let newPhone = "telprompt://" + phoneif let url = URL(string: newPhone) {if UIApplication.shared.canOpenURL(url) {UIApplication.shared.open(url, options: [:], completionHandler: nil)}}}}/// 判断字符串是否为空static func isBlank(_ str: String) -> Bool {let trimmedStr = str.trimmingCharacters(in: .whitespacesAndNewlines)return trimmedStr.isEmpty}}