在MacOS(催化剂应用程序,但AppKit bundle)上,我正在主应用程序菜单中创建共享子菜单" On fly"从像这样的菜单委托:
func menuWillOpen(_ menu: NSMenu) {
self.provider = NSItemProvider(contentsOf: url)! //url points to existing temporary file of type .png
menu.removeAllItems()
let srvcs = NSSharingService.sharingServices(forItems: [self.provider!])
for srv in srvcs {
let it = NSMenuItem(title: srv.menuItemTitle, action: #selector(openSharingService), keyEquivalent: "")
it.image = srv.image
it.representedObject = srv
it.target = self
menu.addItem(it)
}
}
@objc private func openSharingService(sender: NSMenuItem) {
let service = (sender.representedObject as! NSSharingService)
service.perform(withItems: [self.provider!])
}
它适用于任何共享类型,除了发送到照片。与发送到照片,我得到这个错误在控制台:
2021-10-27 08:59:02.042220+0200 Calculator2[14383:7732689] [xpc.exceptions] <NSXPCConnection: 0x6000008470c0> connection to service on pid 14388 named com.apple.share.System.add-to-iphoto.apple-extension-service: Exception caught during decoding of received selector _completeRequestReturningItems:forExtensionContextWithUUID:completion:, dropping incoming message.
Exception: Exception while decoding argument 0 (#2 of invocation):
Exception: value for key 'NS.objects' was of unexpected class 'NSURL (0x7fff801889e8) [/System/Library/Frameworks/CoreFoundation.framework]'. Allowed classes are '{(
"NSDate (0x7fff80188600) [/System/Library/Frameworks/CoreFoundation.framework]",
"NSString (0x7fff801ba8d0) [/System/Library/Frameworks/Foundation.framework]",
"NSNumber (0x7fff801ba3a8) [/System/Library/Frameworks/Foundation.framework]",
"NSData (0x7fff801885d8) [/System/Library/Frameworks/CoreFoundation.framework]",
"NSDictionary (0x7fff80188650) [/System/Library/Frameworks/CoreFoundation.framework]",
"NSArray (0x7fff80188510) [/System/Library/Frameworks/CoreFoundation.framework]"
)}'.
Photos app打开并添加了图片,但是我的app收到了上面的错误,菜单都是灰色的,直到重新启动。我做错什么了吗?
编辑:我试着像这样调用服务(传递NSImage):
self.provider!.loadDataRepresentation(forTypeIdentifier: "public.png", completionHandler: {(data, error) in
let img = NSImage(data: data!)
DispatchQueue.main.async {
service.perform(withItems: [img])
}
})
…它失败了,错误完全相同。再次抱怨NSURL,即使我根本没有通过NSURL。
所以我无法找到错误,但我设法使解决方案。我在函数openSharingService()中添加了以下代码,以便识别Add to Photos并以不同的方式处理它:
if ( (service == NSSharingService(named: .addToIPhoto)) && (self.provider!.hasItemConformingToTypeIdentifier("public.png")) ) {
self.provider!.loadObject(ofClass: NSURL.self, completionHandler: {(val, error) in
//print(val)
DispatchQueue.main.async {
let u = val as! NSURL
self.photosHandler(u)
NSWorkspace.shared.launchApplication("Photos")
}
})
}
自我。photosHandler是一个回调从我的应用的催化剂包填充,它添加照片使用phphotollibrary:
PHPhotoLibrary.requestAuthorization(for: .addOnly, handler: self.OnAuthorizationDone)
(OnAuthorizationDone()也必须实现,使用PHPhotoLibrary.shared().performChanges()
和PHAssetChangeRequest.creationRequestForAssetFromImage()
)