Swiftui:在MacOS上共享Nssharingservice未收到共享

发布于 2025-01-27 04:14:50 字数 4067 浏览 5 评论 0原文

我有一个简单的测试应用程序,该应用程序试图使用NSSharingService与其他用户共享Coredata记录。我可以创建自己的共享,这有效,

”在此处输入图像描述” 但是当我尝试接收共享时,它会打开应用程序,但没有任何操作。

我已经在我的plist中添加了cksharingsupport。

我还遵循了此链接,无济于事: cloudkspcloudkitshare userdidacceptcloudkitsharewarewith of mac app app

mys y y a> mys ya> mys ya> mys ya> mys im code :

SharingServiceApp:

final class AppDelegate: NSObject, NSApplicationDelegate
{
    func application(_ application: NSApplication, userDidAcceptCloudKitShareWith metadata: CKShare.Metadata)
    {
        print ("userDidAcceptCloudKitShareWith")
        let shareStore = persistenceController.sharedPersistentStore!
        persistenceController.container.acceptShareInvitations(from: [metadata], into: shareStore)
        { _, error in
            if let error = error
            {
                print("acceptShareInvitation error :\(error)")
            }
        }
    }
}

contentview:

import SwiftUI
import CoreData
import CloudKit

let persistenceController = PersistenceController()

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext

    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
        animation: .default)
    private var items: FetchedResults<Item>

    var body: some View {
        NavigationView {
            List {
                ForEach(items) { item in
                    NavigationLink {
                        VStack
                        {
                            Text("Item at \(item.timestamp!, formatter: itemFormatter)")
                            Button("Share")
                            {
                                shareRecord(item: item)
                            }
                        }
                        
                    } label: {
                        Text(item.timestamp!, formatter: itemFormatter)
                    }
                }
            }
            .toolbar {
                ToolbarItem {
                    Button(action: addItem) {
                        Label("Add Item", systemImage: "plus")
                    }
                }
            }
            Text("Select an item")
        }
    }

    private func addItem() {
        withAnimation {
            let newItem = Item(context: viewContext)
            newItem.timestamp = Date()

            do {
                try viewContext.save()
            } catch {
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }
}

private let itemFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .short
    formatter.timeStyle = .medium
    return formatter
}()

func shareRecord(item: Item)
{
    Task
    {
        if let share = await createShare(item: item)
        {
            let container = CKContainer(identifier: "iCloud.com.xxxxxxxx.sharingservice")
            
            let item = NSItemProvider()
            item.registerCloudKitShare(share, container: container)
            
            DispatchQueue.main.async
            {
                let sharingService = NSSharingService(named: .cloudSharing)
                sharingService!.perform(withItems: [item])
            }
        }
    }
}

private func createShare(item: Item) async -> CKShare?
{
    do
    {
        let (_, share, _) = try await persistenceController.container.share([item], to: nil)
        share[CKShare.SystemFieldKey.title] = "MyApp"
        return share
    }
    catch
    {
        print("Failed to create share")
        return nil
    }
}

I have a simple test application that attempts to share a CoreData record with another user using NSSharingService. I can create my share and that works,

enter image description herebut when I try to receive the share it opens up the application but doesn't do anything.

I have added CKSharingSupported to my plist.

I have also followed this link to no avail:
CloudKit CKShare userDidAcceptCloudKitShareWith Never Fires on Mac App

Here is my code:

SharingServiceApp:

final class AppDelegate: NSObject, NSApplicationDelegate
{
    func application(_ application: NSApplication, userDidAcceptCloudKitShareWith metadata: CKShare.Metadata)
    {
        print ("userDidAcceptCloudKitShareWith")
        let shareStore = persistenceController.sharedPersistentStore!
        persistenceController.container.acceptShareInvitations(from: [metadata], into: shareStore)
        { _, error in
            if let error = error
            {
                print("acceptShareInvitation error :\(error)")
            }
        }
    }
}

ContentView:

import SwiftUI
import CoreData
import CloudKit

let persistenceController = PersistenceController()

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext

    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
        animation: .default)
    private var items: FetchedResults<Item>

    var body: some View {
        NavigationView {
            List {
                ForEach(items) { item in
                    NavigationLink {
                        VStack
                        {
                            Text("Item at \(item.timestamp!, formatter: itemFormatter)")
                            Button("Share")
                            {
                                shareRecord(item: item)
                            }
                        }
                        
                    } label: {
                        Text(item.timestamp!, formatter: itemFormatter)
                    }
                }
            }
            .toolbar {
                ToolbarItem {
                    Button(action: addItem) {
                        Label("Add Item", systemImage: "plus")
                    }
                }
            }
            Text("Select an item")
        }
    }

    private func addItem() {
        withAnimation {
            let newItem = Item(context: viewContext)
            newItem.timestamp = Date()

            do {
                try viewContext.save()
            } catch {
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }
}

private let itemFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .short
    formatter.timeStyle = .medium
    return formatter
}()

func shareRecord(item: Item)
{
    Task
    {
        if let share = await createShare(item: item)
        {
            let container = CKContainer(identifier: "iCloud.com.xxxxxxxx.sharingservice")
            
            let item = NSItemProvider()
            item.registerCloudKitShare(share, container: container)
            
            DispatchQueue.main.async
            {
                let sharingService = NSSharingService(named: .cloudSharing)
                sharingService!.perform(withItems: [item])
            }
        }
    }
}

private func createShare(item: Item) async -> CKShare?
{
    do
    {
        let (_, share, _) = try await persistenceController.container.share([item], to: nil)
        share[CKShare.SystemFieldKey.title] = "MyApp"
        return share
    }
    catch
    {
        print("Failed to create share")
        return nil
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

昇り龍 2025-02-03 04:14:50

好的,我终于设法让UserDidacceptcloudkitshareharewith被调用。

您需要使用@nsapplicationdelegateadaptor为您的SwiftUi应用程序创建应用程序委托:

@main
struct Sharing_ServiceApp: App
{
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene
    {
        WindowGroup
        {
            ContentView()
                .environment(\.managedObjectContext, persistenceController.container.viewContext)
        }
    }
}

我将该行放入,我的代码立即开始接收共享请求。

OK I have finally managed to get userDidAcceptCloudKitShareWith to be called.

You need to create the app delegate for your SwiftUI app using @NSApplicationDelegateAdaptor:

@main
struct Sharing_ServiceApp: App
{
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene
    {
        WindowGroup
        {
            ContentView()
                .environment(\.managedObjectContext, persistenceController.container.viewContext)
        }
    }
}

I put that line in and my code instantly started receiving the share requests.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文