iOS 将文件共享到任何可能的应用程序的本机方式

iOS native way to share files to any possible apps

我目前正在使用 objective-C 实现一个 iOS 应用程序,它具有用户可以与其他朋友或其他应用程序共享文件的功能(例如将文件上传到 Dropbox,Google 驱动器,将文件附加到邮件,将文件共享到 Facebook Messenger、Whatsapp,通过蓝牙等)。

有没有一种原生的方式来实现这个共享功能,可以检测所有允许共享文件的应用程序,而我不需要一个一个地做?

您想使用 UIActivityViewController。下面是来自 NSHipster, which is probably the most comprehensive article I've seen on the subject. And Apple has some good documentation here.

的示例
NSString *string = ...;
NSURL *URL = ...;

UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[string, URL]
                                applicationActivities:nil];
[navigationController presentViewController:activityViewController
                                  animated:YES
                                completion:^{
     // ...
}];

这为 iPhone 和 iPad 设备提供了完整的答案

ViewController *contentViewController = [[ViewController alloc] init];

// Present the view controller using the popover style.
contentViewController.modalPresentationStyle = UIModalPresentationPopover;
[self presentViewController:contentViewController 
                   animated:YES 
                 completion:nil];

// Get the popover presentation controller and configure it.
UIPopoverPresentationController *presentationController =[contentViewController popoverPresentationController];
presentationController.permittedArrowDirections = UIPopoverArrowDirectionUp;
presentationController.sourceView = self.view;
presentationController.sourceRect = self.view.frame;

UIPopoverPresentationController should have a non-nil sourceView or barButtonItem set before the presentation occurs on iOS 9