Skip to content

Instantly share code, notes, and snippets.

@blork

blork/extensions.m

Last active Dec 13, 2018
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@blork 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