示例工程 41-system-integration

41-system-integration/Sources/Ch41Kit/Integration.swift

swift · 4.6 KB

import Foundation
import SwiftUI
import UniformTypeIdentifiers
 
/// 纯文本文档:`fileImporter`/`fileExporter` 的最小 `FileDocument`。
public struct TextDocument: FileDocument {
    public static var readableContentTypes: [UTType] { [.plainText] }
    public static var writableContentTypes: [UTType] { [.plainText] }
 
    public var text: String
 
    public init(text: String = "") {
        self.text = text
    }
 
    public init(configuration: ReadConfiguration) throws {
        guard let data = configuration.file.regularFileContents else {
            throw CocoaError(.fileReadCorruptFile)
        }
        self = try TextDocument.parse(data)
    }
 
    public static func parse(_ data: Data) throws -> TextDocument {
        guard let text = String(data: data, encoding: .utf8) else {
            throw CocoaError(.fileReadCorruptFile)
        }
        return TextDocument(text: text)
    }
 
    public func encoded() -> Data {
        Data(text.utf8)
    }
 
    public func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
        FileWrapper(regularFileWithContents: encoded())
    }
}
 
/// 安全作用域书签:沙盒里跨启动访问用户选择的文件。
public enum BookmarkStore {
    public static func make(for url: URL) throws -> Data {
        try url.bookmarkData(
            options: .withSecurityScope,
            includingResourceValuesForKeys: nil,
            relativeTo: nil
        )
    }
 
    public static func resolve(_ data: Data) throws -> URL {
        var stale = false
        let url = try URL(
            resolvingBookmarkData: data,
            options: [.withSecurityScope, .withoutUI],
            relativeTo: nil,
            bookmarkDataIsStale: &stale
        )
        if stale {
            throw CocoaError(.fileReadUnknown)
        }
        return url
    }
}
 
/// 拖放载荷:`Transferable` + `Codable`,跨 App 传结构化数据。
public struct BookPayload: Codable, Hashable, Sendable, Transferable {
    public let title: String
    public let author: String
 
    public init(title: String, author: String) {
        self.title = title
        self.author = author
    }
 
    public static var transferRepresentation: some TransferRepresentation {
        CodableRepresentation(contentType: .json)
    }
}
 
/// 深链解析:`myapp://book/<uuid>` → UUID。
public enum DeepLink {
    public enum Route: Equatable, Sendable {
        case book(UUID)
        case settings
    }
 
    public static func parse(_ url: URL) -> Route? {
        guard url.scheme == "myapp" else { return nil }
        guard let host = url.host else { return nil }
        if host == "settings" {
            return .settings
        }
        if host == "book" {
            let id = url.pathComponents.dropFirst().first
            guard let id, let uuid = UUID(uuidString: id) else { return nil }
            return .book(uuid)
        }
        return nil
    }
}
 
/// 通知请求的纯数据:校验标题与延迟,实际调度由系统完成。
public struct NotificationRequest: Equatable, Sendable {
    public let title: String
    public let body: String
    public let delay: TimeInterval
 
    public init(title: String, body: String, delay: TimeInterval = 1) {
        self.title = title
        self.body = body
        self.delay = delay
    }
 
    public var isValid: Bool {
        !title.trimmingCharacters(in: .whitespaces).isEmpty && delay >= 0 && delay <= 60
    }
}
 
/// 截图板:列出本章的集成点。
public struct IntegrationBoard: View {
    public init() {}
 
    private let items: [(String, String)] = [
        ("fileImporter", "选择文件并读取"),
        ("fileExporter", "写出 TextDocument"),
        ("Transferable", "拖放结构化数据"),
        ("Bookmark", "安全作用域书签"),
        ("onOpenURL", "深链解析"),
        ("UserNotifications", "本地通知(需授权)"),
    ]
 
    public var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            Text("系统集成")
                .font(.system(size: 18, weight: .semibold))
            ForEach(items, id: \.0) { item in
                HStack(spacing: 10) {
                    Text(item.0)
                        .font(.system(size: 11, design: .monospaced))
                        .frame(width: 130, alignment: .leading)
                    Text(item.1)
                        .font(.system(size: 11))
                        .foregroundStyle(.secondary)
                    Spacer()
                }
            }
        }
        .padding(18)
        .frame(width: 360, alignment: .leading)
        .background(Color.white)
    }
}