• The author testimonials
  • Introduction to the
  • Create a new project
  • Create a Share the Extension
  • Configuring the Master Application
  • Configure Share the Extension
  • Configuration NSExtension
  • Share the Extension logic
    • Fill in the logic limiting the word length
    • Enter the logic for uploading information
    • Custom UI
  • Supplementary article

The author testimonials

A few days ago I wrote another post about the new features of iOS 8 called Playing with iOS Development: The introduction of Today Extension, a new feature of iOS 8, is one of the features of iOS 8. Due to my busy work, I have been putting it off, so I did not continue to study it. Now I finally have time to study it

Finally: If you have better suggestions or dissatisfaction with this article, please contact me. I will refer to your comments and then modify it. When contacting me, please note the Share Extension

Cain(Lo Ka-fai)

[email protected]: Contact information

350116542: tencent QQ


Introduction to the

What is a Share Extension? In iOS 8, Apple introduced several new features, one of which is Share Extension. You can open Safari, select a website, click On Share, and a sharing interface will appear. The iCon column in the middle is the system’s own Share Extension(as shown in the picture), which is to Share Safari’s website address. Therefore, Share Extension is actually the system’s own social SDK


Create a new project

First of all, we need to create a new project. Since ShareExtension is not an independent application, it depends on the main program, so I have omitted the order of creating the new project. The new project here is called ShareExtensionDemo.


Create a Share the Extension

After creating the new project, we will now create the Share Extension. Just like Today Extension, the system has its own template for us to choose from


Configuring the Master Application

Now that the new project and Share Extension have been created, we can call the Share Extension in the main application to see the effect. I used the StoryBoard for convenience.

Drag a UIButton to the StoryBoard, rename it Share, and associate the Action event with the ViewController, adding the corresponding code.

- (IBAction)ShareAction:(UIButton *)sender {

    NSString *string = @ "hello";

    UIActivityViewController *activityController = [[UIActivityViewController alloc] initWithActivityItems:@[string]
                                                                                     applicationActivities:nil];

    [self presentViewController:activityController
                       animated:YES
                     completion:nil];
}Copy the code

Now let’s look at the corresponding effect ~~

Now that we’ve seen how the Share Extension works, it’s still not enough. Keep going


Configure Share the Extension

Before configuring Share Extension, we need to look at a few methods in it, otherwise we’ll be completely in the dark

// If return No, the send button cannot be clicked, if return YES, the send button can be clicked
- (BOOL)isContentValid {
    // Do validation of contentText and/or NSExtensionContext attachments here
    return YES;
}Copy the code
// Send the button Action event
- (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];
}Copy the code
// This method is a method that returns items as an array
- (NSArray *)configurationItems {
    // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
    return@ []; }Copy the code

Configuration NSExtension

Now that we know the methods above, let’s configure the content rules we can deliver, which are

IOS extensions support media type keys describe instructions
NSExtensionActivationSupportsAttachmentsWithMaxCount Maximum attachment: 20 The attachment includes the following three categories of File, Image and Movie, and the total amount of single and mixed selection does not exceed 20
NSExtensionActivationSupportsAttachmentsWithMinCount Attachment maximum limit: default=1 when the above is not zero By default, at least one attachment is selected and the Extension icon is displayed in [Share Extension]
NSExtensionActivationSupportsWebURLWithMaxCount Maximum number of Web links: default=0 Sharing hyperlinks is not supported by default, such as [Safari]
NSExtensionActivationSupportsFileWithMaxCount Maximum number of files: 20 No more than 20 for single or multiple choices
NSExtensionActivationSupportsWebPageWithMaxCount Maximum number of Web pages: Default =0 Web page sharing is not supported by default, for example [Safari]
NSExtensionActivationSupportsImageWithMaxCount Maximum number of pictures: 20 No more than 20 for single or multiple choices
NSExtensionActivationSupportsVideoWithMaxCount Maximum video limit: 20 No more than 20 for single or multiple choices
NSExtensionActivationSupportsText Text type: default=0 Text sharing is not supported by default, for example [memo]

In fact, this table can be found in the official website documentation ~~


Share the Extension logic

Fill in the logic limiting the word length

First we fill in a few things that limit the number of words that can be entered in the Share Extension, and then add a Share path

Requestb. in/1hx20w61 = 1hx20w61 = 1hx20w61

// A maximum of 40 characters can be entered
static NSInteger const maxCharactersAllowed = 40;
// This is a test connection, it is not fixed, you can go to http://requestb.in to apply, and then replace to your latest application
static NSString *uploadURL = @"http://requestb.in/1hx20w61";Copy the code

So once we’ve declared the word length, we need to implement it in the – (BOOL)isContentValid method

- (BOOL)isContentValid {

    NSInteger length = self.contentText.length;

    self.charactersRemaining = @(maxCharactersAllowed - length);

    return self.charactersRemaining.integerValue < 0 ? NO : YES;
}Copy the code

Enter the logic for uploading information

Here, I use the native network request to send requests. You can also use AFNetWorking. For Swift, you can use another network request framework, Alamofire, whose author is the same god

Before writing the logic, we need to open a Group function of the App and fill in the corresponding parameters, otherwise the data cannot be transmitted.

In the same way, Share Extension needs to do the same operation, so we won’t repeat the operation here. Now we continue to fill in the corresponding network operation logic

First, we need to wrap a method that returns an NSURLRequest

/** * returns an NSURLRequest method that requires passing in an NSString object ** @param string the string to be sent ** @return NSURLRequest */
- (NSURLRequest *)urlRequestWithString:(NSString *)string {

    NSURL *url = [NSURL URLWithString:uploadURL];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

    request.HTTPMethod = @"POST";

    NSMutableDictionary *jsonObject = [NSMutableDictionary dictionary];

    jsonObject[@"text"] = string;

    NSError *jsonError;
    NSData *jsonData;

    jsonData = [NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:&jsonError];

    if (jsonData) {

        request.HTTPBody = jsonData;
    } else {

        NSLog(@"JSON Error: %@", jsonError.localizedDescription);
    }

    return request;
}Copy the code

And then call it in the – (void)didSelectPost click event

- (void)didSelectPost {

    NSString *configName = @"com.shareExtension.ShareExtensionDemo.BackgroundSessionConfig";

    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configName];

    sessionConfig.sharedContainerIdentifier = @"group.ShareExtension";

    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig];

    NSURLRequest *urlRequest = [self urlRequestWithString:self.contentText];

    NSURLSessionTask *task = [session dataTaskWithRequest:urlRequest];

    [task resume];

    [self.extensionContext completeRequestReturningItems:@[] completionHandler:nil];
}Copy the code

It just a matter of, because I don’t know why here with requests for network simulator has been can not only use the real machine test, don’t know if my configuration problem, if you have know the great god of trouble please let us know, thank you ~ ~ now we repeat the start of operation, send the request to the URL specified.

So here we have our Share Extension, simple as it is


Custom UI

In addition, in fact, Share Extension is a UIViewController, so you can customize the UI according to your preferences. For details, you can go to The Official website of Apple or Google, baidu, you know


Supplementary article

NSURLRequest is returned nil. If NSURLRequest is returned nil, it will return nil. If NSURLRequest is returned nil, it will return nil

IOS8 day-by-day – Day2 – Sharing app extension


Making the address

Share Extension project address: github.com/CainRun/Sha…