WWDC2014 app Extensions (app feature sharing)

Source: Internet
Author: User
Tags sqlite

one, about the app Extensions

Extension is a new iOS8 extension mechanism for several fixed system regions, which can make up for the limitation of iOS's sandbox mechanism to the communication between applications to some extent.

The advent of extension provides a convenient way for users to use the services provided in our applications in other applications, such as users can view the brief information of the application display in today's widgets without further access to our application, which would be a new user experience; The presence of extension may reduce the number of times a user starts the application, while also increasing the developer's workload. several key words extension point

In the System support extension area, the extension category also distinguishes accordingly, on the iOS altogether has today, Share, Action, Photo Editing, Storage Provider, Custom keyboard several , in which today's extension are also called widgets.

Each extension point is not used in the same way as it does for dry work, so there is no generic extension. App Extension

That is the extension of this article. Extension is not a stand-alone app, it has a bundle suffix named Bundle,extension in app bundle that is. Appex. The life cycle is different from the ordinary app, which will be described in detail.

Extension cannot exist alone, and must have a containing app that contains it.

In addition, extension require manual activation by the user, and different extension activation methods, such as: Today's widget needs to be activated and closed in today, Custom keyboard need to be set in the settings; Photo Editing needs to be activated or turned off in Photo manager when using photos, Storage Provider can appear when files are selected, Share and Action can be activated in any application, provided that the developer needs to set activation Rules to determine ex Tension need to appear in the right place. Containing app

Although Apple is open to extension, extension in iOS cannot exist alone, and in order to be submitted to the App Store, extension must be included in an app and the implementation part of the app cannot be empty. This app, which contains extension, is called containing app.

The extension will be installed with the containing app installed and unloaded as the containing app is unloaded. Host App

The app, which can be extension, is called the host app, such as the widget's host app. Second, extension and containing app, host app 2.1 extension and host app

The extension and host app can communicate directly with the Extensioncontext property, which is the newly added Uiviewcontroller category:

@interface Uiviewcontroller (nsextensionadditions) <NSExtensionRequestHandling>

//Returns the extension Context. Also acts as a convenience method for a view controller to check if it participating in a extension request.
@property (nonatomic,readonly,retain) nsextensioncontext *extensioncontext Ns_available_ios (8_0);

@end

In fact, extension and host app are implemented through IPC (interprocess communication), but Apple is a highly abstract call interface, we do not need to focus on the underlying things. 2.2 containing app and host app

There is no direct relationship between them and they never need to communicate. 2.3 extension and containing app

The relationship between the two is the most complex, and the entanglement is confusing. Cannot communicate directly

First, although extension's bundle are placed in the containing app's bundle, they are two completely independent processes that cannot communicate directly. However, extension can launch the containing app (and, of course, other apps) in a OpenURL way, but it has to be done by using the host app Extensioncontext:

Launch containing APP
-(void) Openurlcontainingapp
{
    [self.extensioncontext openurl:[nsurl in OpenURL way] urlwithstring:@ "appextension://123"]
                 completionhandler:^ (BOOL success) {
                     NSLog (@ "Open URL result:%d") Success);
                 }];

It is not possible to use OpenURL directly in extension. can share shared resources

Extension and containing apps can work together to read and write a storage area called shared resources, which is implemented via app groups, which will be detailed later in this article.

The relationship between the three can be illustrated by the two images given by the official website:

Containing app can control the appearance and hiding of extension

With the following code, containing app lets extension appear or hide (of course extension can hide it too):

Allow hidden plug-ins to be
showtodayextension-(void)
{
    [ncwidgetcontroller Widgetcontroller] Sethascontent:yes forwidgetwithbundleidentifier:@ "Com.wangzz.app.extension"];
}

Hidden plugins
-(void) hiddetodayextension
{
    [[Ncwidgetcontroller Widgetcontroller] Sethascontent:no forwidgetwithbundleidentifier:@ "Com.wangzz.app.extension"];
}
third, App Groups

This is a new, iOS8 feature that is already available on OS X. It is mainly used for the same group of apps sharing the same read and write space to achieve data sharing.

Extension and containing app share data is a reasonable requirement, such as system stock application, widget and app all need to display several company's stock data, this can be realized through the app groups. 3.1 function Open

To facilitate subsequent operations, make sure that your developer account is logged on Xcode. Open in App

APP groups is located at:

Targets-->appextensiondemo-->capabilities-->app Groups

Found later, the app groups the upper right corner of the switch open, and then choose to add groups, such as mine is Group.wangzz, of course, this is to test casually get the name, regular point of naming rules should be: Group.com.company.app.

After the success of the addition, the following illustration shows:

Open in extension.

I created the widget,target name called Todayextension, and the corresponding app groups is located at:

Targets-->todayextension-->capabilities-->app Groups

As with apps, it's important to keep in mind that the app groups name is the same as the app, which is Group.wangzz. IV, extension and containing app data sharing

App groups provides us with the same area that app can read and write in the same group, which can be shared in the following ways: 4.1 share data by Nsuserdefaults

Save data to Nsuserdefaults in the following ways:

-(void) savetextbynsuserdefaults
{
    nsuserdefaults *shared = [[Nsuserdefaults alloc] initwithsuitename:@ " Group.wangzz "];
    [Shared Setobject:_textfield.text forkey:@ "Wangzz"];
    [Shared synchronize];
}

It is to be noted that:

1. The group ID must be specified when saving data;

2. Also note that Nsuserdefaults can handle the data can only be Plist object, see the property List programming Guide details.

3. In order to prevent data synchronization problems, do not forget to call [shared Synchronize]; Reading data

The corresponding read data method:

-(NSString *) readdatafromnsuserdefaults
{
    nsuserdefaults *shared = [[Nsuserdefaults alloc] Initwithsuitename : @ "Group.wangzz"];
    NSString *value = [Shared valueforkey:@ "Wangzz"];

    return value;
}
4.2 sharing data through Nsfilemanager

Nsfilemanager provides a containerurlforsecurityapplicationgroupidentifier method in iOS7 that can be used to implement app group shared data. Save data

-(BOOL) Savetextbynsfilemanager
{
    nserror *err = nil;
    Nsurl *containerurl = [[Nsfilemanager Defaultmanager] containerurlforsecurityapplicationgroupidentifier:@ " Group.wangzz "];
    Containerurl = [Containerurl urlbyappendingpathcomponent:@ "Library/caches/good"];

    NSString *value = _textfield.text;
    BOOL result = [value Writetourl:containerurl atomically:yes encoding:nsutf8stringencoding error:&err];
    if (!result) {
        NSLog (@ "%@", err);
    } else {
        NSLog (@ "Save value:%@ success.", value);
    }

    return result;
}
Reading data
-(NSString *) Readtextbynsfilemanager
{
    nserror *err = nil;
    Nsurl *containerurl = [[Nsfilemanager Defaultmanager] containerurlforsecurityapplicationgroupidentifier:@ " Group.wangzz "];
    Containerurl = [Containerurl urlbyappendingpathcomponent:@ "Library/caches/good"];
    NSString *value = [NSString stringwithcontentsofurl:containerurl encoding:nsutf8stringencoding error:&err];

    return value;
}

Here I try to save and read the string data, but read and write SQLite I believe it is no problem. Data synchronization

Two applications that read the same data together can cause data synchronization problems. WWDC2014 videos recommend using Nsfilecoordination to achieve read-write synchronization of normal files, while databases can use Coredata,sqlite also support synchronization. v. Extension and containing app code sharing

Similar to data sharing, extension and containing apps naturally have some business-logically-shared code that can be implemented through a framework that has just been used in iOS8. Apple is described in the APP Extension programming Guide:

In IOS 8.0 and later, your can use a embedded framework to share code between your extension and its containing app. For example, if you develop image-processing code this you want both your Photo Editing extension and its containing app T o Share, you can put the "code into" a framework and embed it in both targets.

The framework is embedded into the target of extension and containing app to implement code sharing. But wouldn't it be necessary to copy the framework separately to the main bundle of the extension and containing apps.

Referring to extension and containing app data sharing, I think I can just keep one copy of the framework in the app groups area. 5.1 Copy Framework to app Groups

Put the framework in the app groups area when app first starts:

 
-(BOOL) Copyframeworkfrommainbundletoappgroup {
    Nsfilemanager *manager = [Nsfilemanager Defaultmanager];
    Nserror *err = nil; Nsurl *containerurl = [[Nsfilemanager Defaultmanager] containerurlforsecurityapplicationgroupidentifier:@ "
    Group.wangzz "];
    NSString *sorpath = [NSString stringwithformat:@ "%@/dylib.framework", [[NSBundle Mainbundle] bundlePath]];

    NSString *despath = [NSString stringwithformat:@ "%@/library/caches/dylib.framework", ContainerURL.path];
    BOOL Removeresult = [Manager Removeitematpath:despath error:&err];
    if (!removeresult) {NSLog (@ "%@", err);

    else {NSLog (@ "remove success.");}
    BOOL Copyresult = [[Nsfilemanager Defaultmanager] Copyitematpath:sorpath topath:despath error:&err];
    if (!copyresult) {NSLog (@ "%@", err);

    else {NSLog (@ "copy success.");}
return copyresult; }
5.2 Using the framework:
-(BOOL) loadframeworkinappgroup
{
    nserror *err = nil;
    Nsurl *containerurl = [[Nsfilemanager Defaultmanager] containerurlforsecurityapplicationgroupidentifier:@ " Group.wangzz "];
    NSString *despath = [NSString stringwithformat:@ "%@/library/caches/dylib.framework", ContainerURL.path];
    NSBundle *bundle = [NSBundle Bundlewithpath:despath];
    BOOL result = [Bundle loadandreturnerror:&err];
    if (result) {
        Class root = nsclassfromstring (@ ' person ');
        if (root) {person
            *person = [[Root alloc] init];
            if (person) {
                [person run];}}}
    

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.