How to use NSSharingService in Catalyst?

落爺英雄遲暮 提交于 2020-01-13 05:44:11

问题


I try to use NSSharingService to add my catalyst app to share actions sheet on macOS but get error NSSharingService is unavailable in Mac Catalyst.

#if targetEnvironment(macCatalyst)
extension NSSharingService { //Error: 'NSSharingService' is unavailable in Mac Catalyst
    class func shareContent ( content: [AnyObject], button: NSButton ) {
        let sharingServicePicker = NSSharingServicePicker (items: content )

        sharingServicePicker.showRelativeToRect(button.bounds, ofView: button, preferredEdge: NSRectEdge.MaxY)
    }
}
#endif

I find the article about how to use AppKit in Catalyst here

My steps:

  1. Create macOS ReaderTranslatorAppKit bundle and set principalClass="ReaderTranslatorAppKit.ReaderTranslatorAppKit" in Info.plist
open class ReaderTranslatorAppKit: NSObject, ReaderTranslatorCommonInterfaces {
    public func test() -> String {
        "test 1"
    }
}
  1. Added ReaderTranslatorAppKit bundle in Embed as macOS platform

  2. Create ReaderTranslatorCommonInterfaces common protocol

public protocol ReaderTranslatorCommonInterfaces {
    func test() -> String
}
  1. Load ReaderTranslatorAppKit in SceneDelegate.swift
...
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    if let bundlePath = Bundle.main.builtInPlugInsURL?.appendingPathComponent("ReaderTranslatorAppKit.bundle"),
        let bundle = Bundle(url: bundlePath) {

        bundle.load()

        if let cls = bundle.principalClass as? NSObject.Type,
            let plugin = cls.init() as? ReaderTranslatorCommonInterfaces { //Error: plugin is nil
            print(plugin.test())
        }
        print(bundle)
    }
}

Result I get nil when casting cls.init() as? ReaderTranslatorCommonInterfaces. What's wrong?

Update

I solved my issue by creating macOS project instead of Catalyst, sharing code between two projects and using CFNotificationCenterGetDarwinNotifyCenter and UserDefaults(suitename:) to send objects from my extension to the app here

来源:https://stackoverflow.com/questions/58156217/how-to-use-nssharingservice-in-catalyst

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!