简体   繁体   English

SwiftUI ShareLink分享自定义数据

[英]SwiftUI ShareLink share custom data

I am trying to share a custom struct between two users within the App via ShareLink (UIActivityViewController) in SwiftUI. I created a custom Document Type, the Exported Type Identifier and marked the struct as Transferable.我正在尝试通过 SwiftUI 中的 ShareLink (UIActivityViewController) 在应用程序内的两个用户之间共享一个自定义结构。我创建了一个自定义文档类型、导出类型标识符并将该结构标记为可转移。

However, while I am able to save the example to a file, I would like to send it to another user via AirDrop or similar, st the App appears as an Application Activity.但是,虽然我能够将示例保存到文件中,但我想通过 AirDrop 或类似方式将其发送给另一个用户,但应用程序显示为应用程序活动。

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()
    }
}

文档类型

导出类型标识符

结果,没有分享到应用选项

Have you tried setting the "Conforms To" value in "Exported Type Identifiers" to public.json instead of public.data ?您是否尝试将“导出类型标识符”中的“符合”值设置为public.json而不是public.data After all, your custom struct conforms to Codable and can thus be serialized into JSON. For me this did the trick and Messages started showing up in the share sheet.毕竟,您的自定义结构符合 Codable,因此可以序列化为 JSON。对我来说,这成功了,消息开始出现在共享表中。 When running on a device, I also see AirDrop.在设备上运行时,我还会看到 AirDrop。

What I'm still struggling with is how the receiving app can actually handle the file.我仍在苦苦挣扎的是接收应用程序如何实际处理文件。 I added the LSSupportsOpeningDocumentsInPlace key to Info.plist and set it to YES which causes the file to open in my app by tapping, but then I'm a bit stuck.我将LSSupportsOpeningDocumentsInPlace键添加到Info.plist并将其设置为YES ,这会导致文件通过点击在我的应用程序中打开,但后来我有点卡住了。 Maybe onOpenURL: and decode the JSON file that the URL points to?也许onOpenURL:并解码 URL 指向的 JSON 文件? I found zero results on the inte.net for this, which is a bit surprising.我在 inte.net 上为此找到了零结果,这有点令人惊讶。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM