Share Extension , iOS 8 Feature



How to make my app visible in Safari share options?

Answer is pretty simple ! Using Share Extension , iOS 8 Feature.

My this post describes Apple’s Extensibility feature in iOS 8.  Share Extension 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 we will get share menu 

For example : safari -> click on share button.

Create Xcode project

  1. Create  A demo ShareExtension_9to5iOS  App
  2. Open Xcode
  3. Create new project (File -> New ->Project -> Select IOS -> Application ->Single view Application)
  4. I have name this project  as ShareExtension_9to5iOS
  5. Now Choose a template for new file and create new Cocoa Touch Class name , i have name it as view_IBDesignable And SubClass it to UIView (File ->New->File ->iOS->Source->Cocoa Touch Class->Name it (i have choose ShareExtension_9to5iOS)
  6. Now create Shared extension,  File -> New -> Target(Choose shared extension ) i have name it shareAppExtension.
  7. It will create a group folder having name shareAppExtension with shareAppExtension.h / shareAppExtension.m MainInterface.storyboard /info.plist

 



 

To run your share extension press build and run ,it will ask to choose an app to run and here we choose app Safari 

It will Run and open safari and load its default webpage. 

you will see default buttons at the bottom of safari , here press the share button , it will display a share menu having our app, but if it does not show our app name in this menu then we have to click on more and enable our extension.

Press the post button but it will do nothing.

 



 

So we have to handle delegate methods for it so that when a user click on a post button its content will be share to our application , to set up this we have to code below in our classes.

 

 



Code for ShareViewController.h file

//

//  ShareViewController.h

//  shareAppExtension

//

//  Created by admin on 16/07/18.

//  Copyright © 2018 admin. All rights reserved.

//

#import <UIKit/UIKit.h>

#import <Social/Social.h>

@interface ShareViewController : SLComposeServiceViewController

{

    NSUserDefaults *sharedUserDefaults;

    NSExtensionItem *inputExtensionItem;

}

@end

Code for ShareViewController.m file

//

//  ShareViewController.m

//  shareAppExtension

//

//  Created by admin on 16/07/18.

//  Copyright © 2018 admin. All rights reserved.

//

#import “ShareViewController.h”

@import MobileCoreServices;

static NSString *const AppGrpId = @”group.tag.AppDemoGroup”;

@interface ShareViewController ()

@end

@implementation ShareViewController

– (BOOL)isContentValid {

    // Do validation of contentText and/or NSExtensionContext attachments here

    return YES;

}

– (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.

    inputExtensionItem = self.extensionContext.inputItems.firstObject;

    

    NSItemProvider *urlItemProvider = [[inputExtensionItem.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 *arr_shareLinks;

                 if ([sharedUserDefaults valueForKey:@”9to5iOS_SharedExtension”])

                     arr_shareLinks = [sharedUserDefaults valueForKey:@”SharedExtension”];

                 else

                     arr_shareLinks = [[NSMutableArray alloc] init];

                 NSDictionary *dictSite = [NSDictionary dictionaryWithObjectsAndKeys:self.contentText, @”contentText”, url.absoluteString, @”URL”,nil];

                 [arr_shareLinks addObject:dictSite];

                 [sharedUserDefaults setObject:arr_shareLinks forKey:@”9to5iOS_SharedExtension”];

                 [sharedUserDefaults synchronize];

                 

                 UIAlertController * alert=   [UIAlertController

                                               alertControllerWithTitle:@”9to5Success Alert”

                                               message:@”9to5iOS 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];

             }

         }];

    }

   // [self.extensionContext completeRequestReturningItems:@[] completionHandler:nil];

}

-(void)viewDidLoad

{

    sharedUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:AppGrpId];

    

    // here we must have to provide our app group id that we created

}

– (NSArray *)configurationItems {

    // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.

    return @[];

}

@end

 

Use of AppGroups

If we want our website and content need to be share with our application , for that we have to change setting at AppGroups in iOS, which helps to share data between our application and shared extension.

For this Go to Project  Target and Tap on Capabilites ->Switch On App Groups and add your App groups  name here by pressing + group.tag.AppDemoGroup

Code for ViewController.h file

//

//  ViewController.h

//  ShareExtension_9to5iOS

//

//  Created by admin on 16/07/18.

//  Copyright © 2018 admin. All rights reserved.

//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

{

    NSMutableArray *arr_shareLinks;

    NSUserDefaults *sharedUserDefaults;

}

@end

Code for ViewController.m file

//

//  ViewController.m

//  ShareExtension_9to5iOS

//

//  Created by admin on 16/07/18.

//  Copyright © 2018 admin. All rights reserved.

//

#import “ViewController.h”

static NSString *const AppGrpId = @”group.tag.AppDemoGroup”;

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

}

-(void)viewWillAppear:(BOOL)animated

{

    sharedUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:AppGrpId];

    arr_shareLinks = [NSMutableArray arrayWithArray:[sharedUserDefaults valueForKey:@”9to5iOS_SharedExtension”]];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return arr_shareLinks.count;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *cellIdentifier = @”cellIdentifier”;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if(cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

        

    }

    cell.textLabel.text = [[arr_shareLinks objectAtIndex:indexPath.row] valueForKey:@”URL”];

    cell.detailTextLabel.text = [[arr_shareLinks objectAtIndex:indexPath.row] valueForKey:@”contentText”];

    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[arr_shareLinks objectAtIndex:indexPath.row] valueForKey:@”URL”]]];

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

 

You can download source code from here 



 

Add a Comment

Your email address will not be published. Required fields are marked *