ios:让人们分享 link/image/text 到我的应用

ios: Let people share link/image/text TO my app

如何让我的应用出现在共享 activity Safari、照片等列表中? 我想让人们像在 Facebook 上一样通过我的应用分享 link/image 或发短信。

Facebook/Twitter 等在默认 UIActivityType 列表中可用,但 Pinterest、Zomato 等其他应用程序如何实现这一点?

这是 iOS 8 及更高版本(以及 OS X 10.10 及更高版本)中实现的新功能。它被称为扩展。扩展允许应用程序离开其 Apple 沙箱并访问 OS 的其他部分,包括通知中心和共享表。苹果是这样说的:

Starting in iOS 8.0 and OS X v10.10, an app extension lets you extend custom functionality and content beyond your app and make it available to users while they’re using other apps or the system. You create an app extension to enable a specific task; after users get your extension, they can use it to perform that task in a variety of contexts. For example, if you provide an extension that enables sharing to your social sharing website, users can use it to post a remark while surfing the web. Or if you provide an extension that displays current sports scores, users can put it in Notification Center so that they can get the latest scores when they open the Today view. You can even create an extension that provides a custom keyboard that users can use in place of the iOS system keyboard.

有多种不同类型的扩展程序,包括 Apple Watch 应用程序。您可以在 Apple 文档中查看所有这些类型。

要开始构建扩展,这里有一些资源:

您需要在 info.plist

中使用 UTImportedTypeDeclarations

很好的教程http://www.raywenderlich.com/1948/how-integrate-itunes-file-sharing-with-your-ios-app

最简单的方法是使用文件类型关联。那里已经有很多教程,因为概念已经很成熟,所以我将在这里带您了解主要关键字。

首先要确定的是 Uniform Type Identifiers (UTI) you want to support. Here 是 Apple 当前可用的 UTI 列表。

然后,在您的 Xcode 项目中打开目标,然后转到 Info 选项卡。您会在那里找到 文档类型 条目。 打开它,然后点击加号以添加新的文档类型。指定一个名称和你想要支持的 UTI(在这个例子中我选择了 PDF):

请注意,您还需要提供其他文档属性。大多数教程都将 (LSHandlerRank, Alternate) 作为键值对,但我没有找到任何原因。它似乎也适用于 (foo, bar)

接下来,运行 使您的应用程序在设备上注册。

当你现在有一个 PDF,比如你的邮件应用程序中的一个附件,你的应用程序现在将出现在列表中:

最后,在您的 AppDelegate 中,您需要实现以下方法:

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    NSLog(@"App opened with url %@", url);
    return YES;
}

只要您的应用程序收到 PDF,就会调用它。这些文件将进入一个名为 'Inbox' 的特殊文件夹,url 会告诉您所提供文件的名称。

编辑

这是我的 iPhone:

的示例控制台输出
2015-03-19 15:27:32.841 so 29147257[3951:1529409] App opened with url file:///private/var/mobile/Containers/Data/Application/A5723926-F869-49C0-A2AF-756795932B81/Documents/Inbox/first-1.pdf