ReadViewSDK/Sources/RDReaderView/EPUBCore/RDEPUBWebViewDebug.swift
2026-05-21 19:40:51 +08:00

69 lines
2.6 KiB
Swift

import Foundation
import WebKit
enum RDEPUBWebViewDebug {
static var isEnabled: Bool = {
if let configured = UserDefaults.standard.object(forKey: "RDEPUBWebViewDebugEnabled") as? Bool {
return configured
}
#if DEBUG
return true
#else
return false
#endif
}()
static func webViewID(_ webView: WKWebView?) -> String {
guard let webView else { return "nil-webview" }
return String(ObjectIdentifier(webView).hashValue, radix: 16)
}
static func log(_ scope: String, message: String) {
guard isEnabled else { return }
print("[RDReaderWK][\(scope)] \(message)")
}
static func logNavigationEvent(_ scope: String, webView: WKWebView?, event: String, url: URL? = nil, error: Error? = nil) {
guard isEnabled else { return }
let webViewToken = webViewID(webView)
let urlText = summarizedURL(url)
if let error {
log(scope, message: "webView=\(webViewToken) event=\(event) url=\(urlText) error=\(error.localizedDescription)")
} else {
log(scope, message: "webView=\(webViewToken) event=\(event) url=\(urlText)")
}
}
static func logJavaScript(_ scope: String, webView: WKWebView?, action: String, details: String) {
guard isEnabled else { return }
log(scope, message: "webView=\(webViewID(webView)) js=\(action) \(details)")
}
static func logMessage(_ scope: String, webView: WKWebView?, name: String, body: Any) {
guard isEnabled else { return }
log(scope, message: "webView=\(webViewID(webView)) message=\(name) body=\(String(describing: body))")
}
static func logSchemeTask(_ scope: String, requestURL: URL?, fileURL: URL? = nil, event: String, error: Error? = nil) {
guard isEnabled else { return }
let requestText = summarizedURL(requestURL)
let fileText = summarizedURL(fileURL)
if let error {
log(scope, message: "scheme=\(event) request=\(requestText) file=\(fileText) error=\(error.localizedDescription)")
} else {
log(scope, message: "scheme=\(event) request=\(requestText) file=\(fileText)")
}
}
static func summarizedURL(_ url: URL?) -> String {
guard let url else { return "nil" }
if let scheme = url.scheme, scheme == RDEPUBResourceURLSchemeHandler.scheme {
return url.absoluteString
}
let path = url.path
if path.isEmpty {
return url.absoluteString
}
return url.lastPathComponent.isEmpty ? path : url.lastPathComponent
}
}