Fun iOS development: new feature of iOS 8 “Share Extension”

  • Author comments
  • brief introduction
  • Create a new project
  • Create Share Extension
  • Configuring the main application
  • Configure Share Extension
  • Configuring NSExtension
  • The Share Extension logic writes the logic that limits the number of words, and the logical custom UI to fill the upload information
  • Supplementary article

Author comments

Recently I wrote another article is about the new features of iOS 8, called iOS, developed 8 new features: iOS “Today Extension”, which is one of the 8 iOS to explain the characteristics, due to busy work, it has been dragged, did not pursue the study, now finally have time to pull out you can look at
: if you have a better suggestion or dissatisfaction about this article, please contact me, I will refer to your views to be modified, contact me, please note Share Extension, I wish you all happy to learn ~ ~ thank you

Cain (Luo Jiahui)
QQ: 350116542

brief introduction

What is Share Extension? In iOS 8, apple opened several new features, one of which is Share Extension, you can open their own Apple browser Safari, just select a website, click share, there will be a shared interface, Share Extension comes with the center column is the system (iCon as shown in the figure), it is to use the Safari website address sharing out. So Share Extension is actually the system comes with the social SDK just said so many reasons, not as directly on the code.

Fun iOS development: new feature of iOS 8

Create a new project

First we need to create a new project, because Share Extension is not an independent application, it is necessary to rely on the main program, create a new project order I omitted here, the new project called ShareExtensionDemo.

Fun iOS development: new feature of iOS 8

Create Share Extension

After creating the new project, we now create Share Extension and Today Extension, and the system has its own templates for our own choice

Fun iOS development: new feature of iOS 8
Fun iOS development: new feature of iOS 8
Fun iOS development: new feature of iOS 8
Fun iOS development: new feature of iOS 8

Configuring the main application

Now the new project and Share Extension has been created, we can now in the main application transfer from Share Extension to see the effect, here for convenience, so StoryBoard. is used to drag a UIButton StoryBoard, renamed Share, then associate the Action event to ViewController, add the corresponding code.

Fun iOS development: new feature of iOS 8
Fun iOS development: new feature of iOS 8
Fun iOS development: new feature of iOS 8
Fun iOS development: new feature of iOS 8
- (IBAction) ShareAction: (UIButton * sender) {NSString *string = @ "hello"; UIActivityViewController *activityController = [[UIActivityViewController alloc] initWithActivityItems:@[string] applicationActivities:nil]; [self presentViewController:activityController animated:YES completion:nil];}

Now let’s take a look at the effect

Fun iOS development: new feature of iOS 8
Fun iOS development: new feature of iOS 8
Fun iOS development: new feature of iOS 8

Now we see the Share show out the effect of Extension, but that is not enough, to continue.

Configure Share Extension

Before configuring Share Extension, we need to look at some of the methods, or we’re completely covered

Fun iOS development: new feature of iOS 8
If it is return / / No, then click the send button to return, if YES, then you can click the send button - (BOOL) isContentValid validation of contentText {/ / Do and/or NSExtensionContext attachments here return YES;}
The Action event / / send button - (void) didSelectPost is called after {/ / This 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];}
/ / this method is a method used to return items, and the return value is an array - (NSArray *) configurationItems add configuration options {/ / To via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here. return @[];}

Configuring NSExtension

After we know the methods above, now configure the content rules that we can transfer. These rules are

The iOS extension supports the media type configuration key describe Explain
NSExtensionActivationSupportsAttachmentsWithMaxCount The maximum number of attachments is limited: 20 The annex includes the following three categories of File, Image and Movie, with a single and mixed selection of no more than 20
NSExtensionActivationSupportsAttachmentsWithMinCount Attachments most limited: above non-zero default=1 The default selects at least 1 attachments, and the extension icon is shown in [Share Extension]
NSExtensionActivationSupportsWebURLWithMaxCount Web links limit up to: default=0 Default does not support shared hyperlinks, such as [Safari]
NSExtensionActivationSupportsFileWithMaxCount Maximum file limit: 20 Single or multiple are not more than 20
NSExtensionActivationSupportsWebPageWithMaxCount Web page maximum limit: default=0 Default does not support Web page sharing, such as [Safari]
NSExtensionActivationSupportsImageWithMaxCount Maximum picture limit: 20 Single or multiple are not more than 20
NSExtensionActivationSupportsVideoWithMaxCount Maximum video limit: 20 Single or multiple are not more than 20
NSExtensionActivationSupportsText Text type: default=0 Default does not support text sharing, such as [memo]

In fact, this form can be found in the official website documents ~ ~!

Fun iOS development: new feature of iOS 8

Share Extension logic

Fill in the logic that limits the number of words

First of all we have to fill out a Dongdong, Share Extension is to limit the input word length, and then add a shared path here particularly stressed the need for a little ha, because this link is you need to manually apply, but the effect was, if failed, then go to apply for a to be good.

Limit / / words, can enter up to 40 static NSInteger const maxCharactersAllowed = 40; / / this is a test connection is not fixed, you can go to the application, and then replace the connection to the static can be NSString *uploadURL = @ " you the latest application";

Statement length, word length, we need to go – (BOOL) isContentValid method to achieve

- isContentValid length (BOOL) {NSInteger = self.contentText.length; self.charactersRemaining = @ (maxCharactersAllowed - length); return self.charactersRemaining.integerValue < NO YES;}: 0?

Fill in the logic of uploading information

Here I use the native network request request, you can use AFNetWorking, you can use Swift to another network request frame Alamofire, the authors are the same in writing logic before God, we need a Group function to open the App, and fill in the corresponding parameter, or not transmission of data.

Fun iOS development: new feature of iOS 8
Fun iOS development: new feature of iOS 8

Similarly, the Share Extension also requires the same operation, and there is no repetition of the operation. Now we continue to fill out the corresponding network operation logic

Fun iOS development: new feature of iOS 8

First of all, we need to encapsulate a method to return NSURLRequest

/ * * * returns a NSURLRequest method, need to pass a NSString * * @param string needs to send out the string * * @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:json Object options:NSJSONWritingPrettyPrinted error:& jsonError]; if (jsonData) {request.HTTPBody = jsonData;} else {NSLog ("JSON Error: @% @", jsonError.localizedDescription);} return request;}

Then call 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];}

This was done here, because I don’t know why has been unable to use the simulator network request, only the test machine, I do not know whether the configuration of the problem, if there is to know god please inform me, thank you ~ ~ now we’ll repeat the first operation, sends a request to the specified go URL.

Fun iOS development: new feature of iOS 8
Fun iOS development: new feature of iOS 8

That we can fix Share Extension, very simple

Custom UI

Here to add, in fact it is a Share Extension UIViewController to UI, so you can customize according to your preferences, details you can go to Apple’s official website or the Google search, Baidu, you know

Supplementary article

Here, add another article, about Share Extension, is written in Swift, there are some problems, will lead to NSURLRequest return to nil, we step by step debugging, you know why

IOS8 Day-by-Day – Day2 – share application extensions

GitHub address

Share Extension engineering address: