This question may have been asked previously in a different form, but I am attempting a slightly deeper attempt at understanding Share extensions and therefore, this question has more detail than the previously asked version of this question.
When writing a Share Extension, we can subclass SLComposeServiceViewController and get the viewDidLoad() and didSelectPost() events among others, but the only properties on the VC are contentText and textView and placeholder properties according to Apple documentation
https://developer.apple.com/library/prerelease/ios/documentation/Social/Reference/SLComposeServiceViewController_Class/
Given that this is the case, what is the best way of doing the following :
Firstly, populating the VC that appears with the URL of the website
Secondly, Accessing the URL to pass to the sharedDefaults as follows
let shareDefaults = NSUserDefaults(suiteName: "groupName")
shareDefaults?.setObject(self.contentText, forKey: "stringKey")
shareDefaults?.synchronize()
so as to be able to save it for later access from the app.
Any help regarding getting the URL would be greatly appreciated.
You can access the URL like this:
- (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) {
// Do what you want to do with url
[self.extensionContext completeRequestReturningItems:@[]
completionHandler:nil];
}];
}
}
Here is the same in 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 {
// do what you want to do with shareURL
}
self.extensionContext?.completeRequestReturningItems([], completionHandler:nil)
})
}
}
}
}
Updated for Swift 5:
override func didSelectPost() {
if let item = extensionContext?.inputItems.first as? NSExtensionItem {
if let itemProvider = item.attachments?.first {
if itemProvider.hasItemConformingToTypeIdentifier("public.url") {
itemProvider.loadItem(forTypeIdentifier: "public.url", options: nil, completionHandler: { (url, error) -> Void in
if let shareURL = url as? NSURL {
// do what you want to do with shareURL
}
self.extensionContext?.completeRequest(returningItems: [], completionHandler:nil)
})
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With