在iOS上的Safari的共享扩展中获取SLComposeServiceViewController中的URL

前端之家收集整理的这篇文章主要介绍了在iOS上的Safari的共享扩展中获取SLComposeServiceViewController中的URL前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这个问题之前可能已经以不同的形式提出过,但我正在尝试稍微深入一点地理解共享扩展,因此,这个问题比之前提出的问题版本更详细.

在编写Share扩展时,我们可以继承SLComposeServiceViewController并获取viewDidLoad()和didSelectPost()事件等,但VC上的唯一属性是contentText和textView以及根据Apple文档的占位符属性

https://developer.apple.com/library/prerelease/ios/documentation/Social/Reference/SLComposeServiceViewController_Class/

鉴于这种情况,执行以下操作的最佳方式是什么:

首先,使用网站的URL填充显示的VC

其次,访问URL以传递给sharedDefaults,如下所示

  1. let shareDefaults = NSUserDefaults(suiteName: "groupName")
  2. shareDefaults?.setObject(self.contentText,forKey: "stringKey")
  3. shareDefaults?.synchronize()

以便能够保存它以便以后从应用程序访问.

任何有关获取URL的帮助将不胜感激.

解决方法

您可以像这样访问URL:
  1. - (void)didSelectPost {
  2. NSExtensionItem *item = self.extensionContext.inputItems.firstObject;
  3. NSItemProvider *itemProvider = item.attachments.firstObject;
  4. if ([itemProvider hasItemConformingToTypeIdentifier:@"public.url"]) {
  5. [itemProvider loadItemForTypeIdentifier:@"public.url"
  6. options:nil
  7. completionHandler:^(NSURL *url,NSError *error) {
  8. // Do what you want to do with url
  9. [self.extensionContext completeRequestReturningItems:@[]
  10. completionHandler:nil];
  11. }];
  12. }
  13. }

Swift中的情况也是如此:

  1. override func didSelectPost() {
  2. if let item = extensionContext?.inputItems.first as? NSExtensionItem {
  3. if let itemProvider = item.attachments?.first as? NSItemProvider {
  4. if itemProvider.hasItemConformingToTypeIdentifier("public.url") {
  5. itemProvider.loadItemForTypeIdentifier("public.url",options: nil,completionHandler: { (url,error) -> Void in
  6. if let shareURL = url as? NSURL {
  7. // do what you want to do with shareURL
  8. }
  9. self.extensionContext?.completeRequestReturningItems([],completionHandler:nil)
  10. })
  11. }
  12. }
  13. }
  14. }

猜你在找的iOS相关文章