iOS共享扩展程序在Swift中抓取URL

xyz*_*123 10 ios swift ios-extensions

我正在尝试在swift中创建一个iOS共享扩展.当用户在Safari中并打开共享扩展时,我希望能够获取URL并在我的应用程序中使用它.我知道我可以将下面的代码放在ShareViewController的didSelectPost()函数中,以获取用户在共享扩展中输入的文本,但是如何获取用户点击共享时所在网页的URL延期?我对iOS扩展很新,所以任何帮助都会非常感激.

 let shareDefaults = NSUserDefaults(suiteName: "groupName")
 shareDefaults?.setObject(self.contentText, forKey: "stringKey")
 shareDefaults?.synchronize()
Run Code Online (Sandbox Code Playgroud)

joe*_*ern 22

这是您获取URL的方式:

- (void)didSelectPost {
    NSExtensionItem *item = self.extensionContext.inputItems.firstObject;
    NSItemProvider *itemProvider = item.attachments.firstObject;
    if ([itemProvider hasItemConformingToTypeIdentifier:@"public.url"]) {
        [itemProvider loadItemForTypeIdentifier:@"public.url"
                                        options:nil
                              completionHandler:^(NSURL *url, NSError *error) {
                                  NSString *urlString = url.absoluteString;
                                  // send url to server to share the link
                                  [self.extensionContext completeRequestReturningItems:@[]         
                                                                     completionHandler:nil];
                              }];
    }
}
Run Code Online (Sandbox Code Playgroud)

或者在Swift中:

override func didSelectPost() {
    if let item = extensionContext?.inputItems.first as? NSExtensionItem {
        if let itemProvider = item.attachments?.first as? NSItemProvider {
            if itemProvider.hasItemConformingToTypeIdentifier("public.url") {
                itemProvider.loadItemForTypeIdentifier("public.url", options: nil, completionHandler: { (url, error) -> Void in
                    if let shareURL = url as? NSURL {
                        // send url to server to share the link
                    }
                    self.extensionContext?.completeRequestReturningItems([], completionHandler:nil)
                })
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 14

这有一个很小的变化.在Chrome中,public.url位于第1项,而不是附件的第0项.循环找到它更好,并将在chrome和safari上工作.

if let item = extensionContext?.inputItems.first as? NSExtensionItem {
    if let attachments = item.attachments as? [NSItemProvider] {
        for attachment: NSItemProvider in attachments {
            if attachment.hasItemConformingToTypeIdentifier("public.url") {
                attachment.loadItemForTypeIdentifier("public.url", options: nil, completionHandler: { (url, error) in
                    if let shareURL = url as? NSURL {
                        // Do stuff with your URL now. 
                    }
                    self.extensionContext?.completeRequestReturningItems([], completionHandler:nil)
                })
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 上例中的附件是否应包含com.apple.property-list?我似乎无法找出这一点。使用上面的代码,我没有得到URL。由于未在com.apple.property-list中似乎没有“ public.url”,因此completedHandler无法执行 (2认同)