示例工程 41-system-integration
41-system-integration/Sources/Ch41Demo/App.swift
import AppKit
import Ch41Kit
import SwiftUI
@main
struct Ch41Demo {
@MainActor
static func main() {
do {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("ch41-doc-\(UUID().uuidString).txt")
try "hello".write(to: url, atomically: true, encoding: .utf8)
let data = try Data(contentsOf: url)
let document = try TextDocument.parse(data)
print("[41.1] 文档读取 = \(document.text)")
try? FileManager.default.removeItem(at: url)
} catch {
print("[41.1] 文档读取失败 = \(error)")
}
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("ch41-bookmark-\(UUID().uuidString).txt")
try? "bookmark".write(to: url, atomically: true, encoding: .utf8)
do {
let data = try BookmarkStore.make(for: url)
let resolved = try BookmarkStore.resolve(data)
print("[41.2] 书签解析 = \(resolved.lastPathComponent == url.lastPathComponent)")
} catch {
print("[41.2] 书签解析失败 = \(error)")
}
try? FileManager.default.removeItem(at: url)
let uuid = UUID(uuidString: "11111111-2222-3333-4444-555555555555")!
let parsed = DeepLink.parse(URL(string: "myapp://book/\(uuid.uuidString)")!)
if case .book(let id) = parsed {
print("[41.3] 深链 = book:\(id.uuidString)")
} else {
print("[41.3] 深链 = nil")
}
print(
"[41.4] 非法深链 = \(DeepLink.parse(URL(string: "https://example.com")!) == nil ? "nil" : "unexpected")"
)
let payload = BookPayload(title: "Swift", author: "Apple")
if let data = try? JSONEncoder().encode(payload) {
print("[41.5] 载荷 JSON 字节 = \(data.count)")
}
let request = NotificationRequest(title: "完成", body: "导出成功", delay: 2)
print("[41.6] 通知请求有效 = \(request.isValid)")
print("[41.7] 集成板渲染 = \(size(IntegrationBoard()))")
print("[41.8] MemoryLayout<BookPayload> = \(MemoryLayout<BookPayload>.size) 字节")
if let directory = ProcessInfo.processInfo.environment["SHOTS_DIR"] {
write(IntegrationBoard(), name: "integration-board.png", directory: directory)
}
}
@MainActor
private static func size(_ view: some View) -> String {
guard let image = ImageRenderer(content: view).cgImage else { return "nil" }
return "\(image.width)x\(image.height)"
}
@MainActor
private static func write(_ view: some View, name: String, directory: String) {
let renderer = ImageRenderer(content: view)
renderer.scale = 2
guard
let image = renderer.cgImage,
let data = NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:])
else {
print("[41.9] 截图失败:\(name)")
return
}
let url = URL(fileURLWithPath: directory).appendingPathComponent(name)
do {
try FileManager.default.createDirectory(
at: url.deletingLastPathComponent(),
withIntermediateDirectories: true
)
try data.write(to: url)
print("[41.9] 截图 = \(name) \(image.width)x\(image.height)")
} catch {
print("[41.9] 截图失败:\(error)")
}
}
}