Skip to content

Instantly share code, notes, and snippets.

@blork
Last active May 20, 2021 14:25
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blork/3908619597ab4515941d to your computer and use it in GitHub Desktop.
Save blork/3908619597ab4515941d to your computer and use it in GitHub Desktop.
Dealing with various extension data types
NSExtensionItem *item = self.extensionContext.inputItems.firstObject;
NSItemProvider *itemProvider = item.attachments.firstObject;
// Shared plain text is stored here. Content varies wildly based on app.
NSString *sharedPlainText = [item.attributedContentText string];
if ([itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypePropertyList]) {
[itemProvider loadItemForTypeIdentifier:(NSString *)kUTTypePropertyList
options:nil
completionHandler:^(NSDictionary *item, NSError *error) {
// If it's a "webpage". This type seems to be mostly shared by Safari.
// We can run custom JS if it's a webpage, so get more info that way
// e.g. page title, currently selected text, etc.
NSDictionary *results = [item objectForKey:NSExtensionJavaScriptPreprocessingResultsKey];
// Probably don't need sharedPlainText here since we can get
// lots of info from the page itself
}];
} else if ([itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypeURL]) {
[itemProvider loadItemForTypeIdentifier:(NSString *)kUTTypeURL options:nil completionHandler:^(NSURL *url, NSError *error) {
// Maybe it's just a URL
// May want to use sharedPlainText as well, maybe as the title
}];
} else if (sharedPlainText) {
// Or maybe it's plain text only
// Could use an NSDataDetector to get a URL out of it, if possible
} else {
// Or maybe there's nothing at all <flanders.gif>
// Not sure why this would happen, might be a beta bug.
// I managed to get it when sharing the calendar event from apple.com/live :/
}
@blork
Copy link
Author

blork commented Sep 5, 2014

To get info from a "webPage" type, it seems like you really need a JS preprocessor file. You can set this in your extension's Info.plist with the key NSExtensionJavaScriptPreprocessingFile inside the NSExtensionAttributes dictionary. See https://gist.github.com/blork/e2780fd7e2a1a95f57d3 for an example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment