且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

iOS应用扩展 - 操作 - 自定义数据

更新时间:2023-11-22 14:42:34

统一类型标识符确实是执行此操作的正确方法。

Uniform Type Identifiers are indeed the correct way to do this.

我还没有完成这个,但我设法让它最低限度地工作。基本上,您定义了一个自定义类型,如 com.company.app.myThing ,您可以将自定义对象作为哈希传递给您想要的任何数据结构。显然消费者需要知道并遵循这种模式。

I have not finished developing this, but I managed to get it minimally working. Basically you define a custom type like com.company.app.myThing and you can pass your custom object as a hash with whatever data structure you want. Obviously the consumer needs to know and follow this schema.

这是 info.plist 的相关部分。扩展名:

Here is the relevant portion of info.plist in the extension:

<key>NSExtensionAttributes</key>
<dict>
  <key>NSExtensionActivationRule</key>
  <string>SUBQUERY(extensionItems, $extensionItem, SUBQUERY($extensionItem.attachments, $attachment, ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO &quot;com.company.app.myThing&quot;).@count == 1).@count == 1</string>
  <key>NSExtensionPointName</key>
  <string>com.apple.ui-services</string>
  <key>NSExtensionPointVersion</key>
  <string>1.0</string>
</dict>

在扩展程序的 ActionViewController.viewDidLoad 中:

let item = self.extensionContext.inputItems[0] as NSExtensionItem
let provider = (item.attachments as Array<NSItemProvider>)[0] as NSItemProvider
provider.loadItemForTypeIdentifier("com.company.app.myThing", options: nil, completionHandler: { msg, error in
    let my_thing = (msg as? NSDictionary) as Dictionary<String, AnyObject>
    // do stuff with my_thing
})

然后在主机应用程序中:

Then in the host app:

let my_thing = [
  "foo": "bar",
  "baz": 123
]
let item = NSExtensionItem()
let attachment = NSItemProvider(item: my_thing, typeIdentifier: "com.company.app.myThing")
item.attachments = [attachment]
let activityViewController = UIActivityViewController(activityItems: [item], applicationActivities: nil)
self.presentViewController(activityViewController, animated: true, completion: actionComplete)

免责声明:请做不要认为这是一个权威的方法,但我希望它可以指出你正确的方向。

DISCLAIMER: Please do not consider this an authoritative how-to, but I hope it can point you in the right direction.