wake-ios/wake/SharedUI/Media/SVGImageHtml.swift

71 lines
2.4 KiB
Swift

import SwiftUI
import WebKit
struct SVGImageHtml: UIViewRepresentable {
let svgName: String
func makeUIView(context: Context) -> WKWebView {
let webView = WKWebView()
webView.isOpaque = false
webView.backgroundColor = .clear
webView.scrollView.isScrollEnabled = false
webView.scrollView.contentInsetAdjustmentBehavior = .never
// 1. Get the URL for the SVG file
guard let path = Bundle.main.path(forResource: svgName, ofType: "svg") else {
print("❌ Cannot find SVG file: \(svgName).svg in bundle")
return webView
}
let fileURL = URL(fileURLWithPath: path)
do {
// 2. Read the SVG content directly
let svgString = try String(contentsOf: fileURL, encoding: .utf8)
// 3. Create HTML with inline SVG for better reliability
let htmlString = """
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<style>
body, html {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
background-color: transparent;
display: flex;
justify-content: center;
align-items: center;
}
svg {
max-width: 100%;
max-height: 100%;
}
</style>
</head>
<body>
\(svgString)
</body>
</html>
"""
// 4. Load the HTML with base URL as the main bundle's resource path
if let resourcePath = Bundle.main.resourceURL {
webView.loadHTMLString(htmlString, baseURL: resourcePath)
} else {
webView.loadHTMLString(htmlString, baseURL: nil)
}
} catch {
print("❌ Error loading SVG file: \(error.localizedDescription)")
}
return webView
}
func updateUIView(_ uiView: WKWebView, context: Context) {}
}