Share Extensions Part 1

Episode #144 | 19 minutes | published on November 11, 2014
Subscribers Only
In this episode we create an application and share extension that lets us post to the Imgur API. We use a Framework to share API code between application and extension, and we leverage App Groups so that background sessions transfer across both as well.

Episode Links

Share Extension

We'll use the ShareViewController which simplifies things for sharing simple content. It contains an attached image and a place to enter text. We can control when the content is considered valid and the Post button is enabled.

Loading the Content from the Host App

We need to extract the content being shared from the host app. You can do this in viewDidLoad however Apple recommends against this because you'll be taxing the system during an animation, and it may stutter. Instead, there is a new hook we can use: - presentationAnimationDidFinish

- (void)presentationAnimationDidFinish {
    for (NSExtensionItem *item in self.extensionContext.inputItems) {
        for (NSItemProvider *provider in item.attachments) {
            NSString *imageType = (NSString *)kUTTypeImage;
            if ([provider hasItemConformingToTypeIdentifier:imageType]) {
                [provider loadItemForTypeIdentifier:imageType
                                            options:nil
                                  completionHandler:^(NSURL *imageURL, NSError *error) {
                                      if (error) {
                                          NSLog(@"ERROR: %@", error);
                                      } else {
                                          NSLog(@"Got image url: %@", imageURL);
                                          self.imageURL = imageURL;
                                          return;
                                      }
                                  }];
            }
        }
    }
}

This code looks quite a bit worse in Swift because we can't take any of the types for granted. Objective-C allows us to make some assumptions, at the expense of a little safety.

The purpose of the above method is to save the imageURL that we need to post. We can do that when the user taps the Post button.

Overriding isContentValid will allow us to control when the Post button is enabled:

- (BOOL)isContentValid {
    return (self.imageURL != nil && self.contentText.length > 0);
}

When this method returns true, the button is enabled. Here we're just forcing some text, but we have no upper limit like you would with Twitter.

Handling the Post


- (void)didSelectPost {
    NSLog(@"Do upload...");

    // Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context.
    [self.extensionContext completeRequestReturningItems:@[] completionHandler:nil];
}

The upload will come in the next episode...

blog comments powered by Disqus