Skip to main content

Share Extension in iOS 8

Share Extension




Objective

This blog post briefly describes Apple’s Extensibility feature in iOS 8. It allows you to extend custom functionality and its content of your application, and available it for user when they are using other applications.
App extension allows access to Share menu with any of available service like action for available browser. Extensions are available along with its related app. So, if you want extension then you must have to install its associated application.
There are the numbers of extensions available in iOS 8 while apple also introduces widgets and custom keyboards as extension. Number of available extensions are describe as per following.
  • Share
  • Action
  • Photo Editing
  • Storage Provider
  • Today (Widgets)
  • Custom Keyboard
But, here we are focusing on how to use and implement share extension in iOS8. Share extension provides easier way when you are working with iOS8. It allows you to share any kind of content directly with your application or any website.
Share Extension can be used by clicking on share button in any of application and you will get share menu as following image. For Example, Go to safari >> tap on share button.
You will get something like following:

tap-on-share-button

Share menu will be available with options available in top menu like Mail, Twitter, Facebook and More options. When you tape on More button you will get something like following image.

more-button

Here you can see the list of all installed extensions, it also enables those that you want to use and disable those that you won’t. It also allows you to reorder available extensions by tapping on it and move it up and down.
Following are the steps to implement ShareExtension. Here we are creating and extension that allows you to share website link and content from the available browsers to your application.

Step 1 Create Xcode project

First of all create new Xcode project and named it as ShareSheetBlogExample and choose the location where you actually want to sore it.
  • create-new-xcode-project
  •  
  • location




Step 2 Create Shared extension

Now create Shared extension, for that go to File >> New >> Target
target
Choose shared extension as following:
share-extenstion

Step 3 Give appropriate name & save

Give appropriate name and save it. It will ask you as following, choose Activate.
acrtivate
It will include following list of file in your project folder:
project-folder

Step 4 Run app using Safari

Now build and run your extension by choosing extension from active scheme as following. 
build-and-run-extension
It will ask you to choose an app to run , here we are going to select safari and press run. 
choose-an-app-to-run
It will directly open safari and load webpage. Now click on share button and share menu will be displayed. Our extension automatically installed in top menu as following. if you don’t get extension then click on more and enable your extension respectively. 
share-button
Now click on that and you will get as following:
get-as-following
Composer sheet is available with content and image. Click on the Post button. But it happens nothing. Now if you want to handle delegate method for that and when user click on post button, respected content will be share to your application you have go through the following number of steps.
Following steps describe line of code that you have to written in your share extension class files.

Step 5 Code for ShareViewController.h file

Now click on ShareViewController.h file and write following line of code.
#import <UIKit/UIKit.h>
#import <Social/Social.h>

@interface ShareViewController : SLComposeServiceViewController
{
      NSUserDefaults *sharedUserDefaults;
      NSExtensionItem *inputItem;
}
@end



Step 6 Use of AppGroups

Now we want our content and website link will be shared with our application for that we must have to use AppGroups in iOS. It helps you to share data between your application and shared extension.
When user will click on post button following method will be called.
- (void)didSelectPost
{
      // This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.

      // 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];
}


Step 7 Code for ShareViewController.m file

Write following line of code in your ShareViewController.m file
#import "ShareViewController.h"
@import MobileCoreServices;

static NSString *const AppGroupId = @"group.tag.AppGroupDemo";

@interface ShareViewController ()
@end
@implementation ShareViewController

- (BOOL)isContentValid
{
      // Do validation of contentText and/or NSExtensionContext attachments here
      return YES;
}

-(void)viewDidLoad
{
      sharedUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:AppGroupId];
     // here you must have to provide your app group id that you already created
}




Step 8 Code for didSelectPost method

Write following line of code in didSelectPost() method as following.
- (void)didSelectPost
{
      // This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.

      // 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.

      inputItem = self.extensionContext.inputItems.firstObject;
      NSItemProvider *urlItemProvider = [[inputItem.userInfo valueForKey:NSExtensionItemAttachmentsKey] objectAtIndex:0];

    if ([urlItemProvider hasItemConformingToTypeIdentifier:(__bridge NSString *)kUTTypeURL])
     {
         [urlItemProvider loadItemForTypeIdentifier:(__bridge NSString *)kUTTypeURL options:nil                   completionHandler:^(NSURL *url, NSError *error)
         {
             if (error)
              {
                   NSLog(@"Error occured");
              }
         else
             {
                 NSMutableArray *arrSites;
                 if ([sharedUserDefaults valueForKey:@"SharedExtension"])
                     arrSites = [sharedUserDefaults valueForKey:@"SharedExtension"];
                else
                    arrSites = [[NSMutableArray alloc] init];
                    NSDictionary *dictSite = [NSDictionary dictionaryWithObjectsAndKeys:self.contentText, @"Text", url.absoluteString, @"URL",nil];
                    [arrSites addObject:dictSite];
                    [sharedUserDefaults setObject:arrSites forKey:@"SharedExtension"];
                    [sharedUserDefaults synchronize];

                   UIAlertController * alert= [UIAlertController alertControllerWithTitle:@"Success"
message:@"Posted Successfully." preferredStyle:UIAlertControllerStyleAlert];
                  UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
                 {
                      [UIView animateWithDuration:0.20 animations:^{
            self.view.transform = CGAffineTransformMakeTranslation(0, self.view.frame.size.height);
                 }
          completion:^(BOOL finished)
                 {
                     [self.extensionContext completeRequestReturningItems:nil completionHandler:nil];
                }];
         }];

             [alert addAction:ok];
             [self presentViewController:alert animated:YES completion:nil];
        }
    }];
   }
}
Now, when you will run shared extension and share data with your extension, website link and your content will be saved to user defaults via app groups. Now you have to access it through your application and display it in UITableView.

Step 9 Code for ViewController.h file

For that you have to write following line of code in ViewController.h file of your project.
#import <UIKit/UIKit.h>
#import "WebCell.h"

@interface ViewController : UIViewController
{
     NSMutableArray *arrSites;
     NSUserDefaults *sharedUserDefaults;
}
@end


Step 10 Code for ViewController.m file

Please write following line of in your ViewController.m file. Which data we get that we shared through extension and display it in table view.
#import "ViewController.h"

static NSString *const AppGroupId = @"group.tag.AppGroupDemo";

@interface ViewController ()
@end
@implementation ViewController

- (void)viewDidLoad
{
     [super viewDidLoad];
}

-(void)viewWillAppear:(BOOL)animated
{
     sharedUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:AppGroupId];
     arrSites = [NSMutableArray arrayWithArray:[sharedUserDefaults valueForKey:@"SharedExtension"]];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
      return arrSites.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
      WebCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
      cell.lblSite.text = [[arrSites objectAtIndex:indexPath.row] valueForKey:@"URL"];
      cell.lblContent.text = [[arrSites objectAtIndex:indexPath.row] valueForKey:@"Text"];
      return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[arrSites objectAtIndex:indexPath.row] valueForKey:@"URL"]]];
}
ScreenShots:  
  • my-list
  •  
  • final-output1

I hope you find this blog is very helpful while working on Share Extension in iOS 8. Let me know in comment if you have any questions regarding iOS 8. I will reply you ASAP.

Comments

Popular Posts

Master Map & Filter, Javascript’s Most Powerful Array Functions

Master Map & Filter, Javascript’s Most Powerful Array Functions Learn how Array.map and Array.filter work by writing them yourself This article is for those who have written a  for  loop before, but don’t quite understand how  Array.map  or  Array.filter  work. You should also be able to write a basic function. By the end of this, you’ll have a complete understanding of both functions, because you’ll have seen how they’re written. Array.map Array.map  is meant to transform one array into another by performing some operation on each of its values. The original array is left untouched and the function returns a new, transformed array. For example, say we have an array of numbers and we want to  multiply each number by three . We also don’t want to change the original array. To do this without  Array.map , we can use a standard for-loop. for-loop var originalArr = [1, 2, 3, 4, 5]; var newArr = []; for(var i = 0; i < originalArr.length; i+...

Integrate the FaceID or TouchID Authentication in iOS Apps - Swift

FaceID or TouchID Authentication Dear Folks, today I am going to explain the proper way to integrate the Face ID or Touch ID in iOS App. Face ID and Touch ID are secure, familiar authentication methods that people trust. Follow below steps: Step 1: Add NSFaceIDUsageDescription Key in info.plist file <key>NSFaceIDUsageDescription</key> <string>This app requires Face ID permission to authenticate using Face recognition.</string> Step 2: Create a swift file with any name but it would be better to related to its functionality, Like BioMetrixFile.swift Step 3: In BioMetrixFile write below codes and follow instructions. But before proceeding further import LocalAuthentication class in BioMetrixFile. Now, create typealias for success or failure blocks to well manage Authentication Success or Failure. public typealias AuthenticationSuccess = (() -> ()) public typealias AuthenticationFailure = ((AuthenticationError) -> ()) Now written all s...

React Native: How To Open App Settings Page

  React Native: How To Open App Settings Page React Native has a Linking module to manage the interaction with other applications in the device. In this article, I will explain how you can open “Application Setting Page” of the device using. Sample Case Before I explain how to do this, I’ll talk about an example case where we might need this: You need to get location permission within the application from a user using an iOS operating system and you asked for permission. But user did not agree to grant this permission the first time. In this case, you cannot ask your user for location permission the second time. In this case, the only thing to do is to direct the user to the settings page of our application and make it manually allow it. Now that we have explained our example situation, we can move on to how we can redirect our user to the “settings page of our application”. Open App Settings Page iOS If our user is using an iOS operating system, we can handle the whole process wit...