SwiftUI ShareLink共享自定义数据

8wigbo56  于 2023-01-08  发布在  Swift
关注(0)|答案(1)|浏览(152)

我尝试通过SwiftUI中的ShareLink(UIActivityViewController)在应用程序内的两个用户之间共享自定义结构体。我创建了自定义文档类型、导出类型标识符并将结构体标记为可传输。
然而,虽然我能够将示例保存到文件中,但我想通过AirDrop或类似方式将其发送给另一个用户,S.T.应用程序显示为应用程序活动。

import SwiftUI
import UniformTypeIdentifiers

struct SwiftUIView: View {
    @State private var customStruct: CustomStruct = CustomStruct()
    var body: some View {
        ShareLink(item: customStruct, preview: SharePreview(customStruct.name))
    }
}

struct CustomStruct: Codable {
    var name: String = "Test Example"
    var description: String = "Test"
}

extension CustomStruct: Transferable {
    static var transferRepresentation: some TransferRepresentation {
        CodableRepresentation(contentType: .customStruct)
    }
}

extension UTType {
    static var customStruct: UTType { UTType(exportedAs: "com.TestExample.CustomStruct") }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView()
    }
}

pcww981p

pcww981p1#

您是否尝试过将“导出的类型标识符”中的“Conforms To”值设置为public.json而不是public.data?毕竟,您的自定义结构符合Codable,因此可以序列化为JSON。对我来说,这确实起到了作用,消息开始显示在共享表中。当在设备上运行时,我还可以看到AirDrop。
我还在纠结的是接收应用程序实际上如何处理文件。我在Info.plist中添加了LSSupportsOpeningDocumentsInPlace键,并将其设置为YES,这会导致文件在我的应用程序中通过点击打开,但随后我有点卡住了。也许onOpenURL:并解码URL指向的JSON文件?我在互联网上没有找到任何相关结果,这有点令人惊讶。

相关问题