Share data between two or more iPhone applications

2019-01-01 05:07发布

问题:

Is this possible to share data between two applications on the same device?

Or can I allow some other application to use my application\'s information / data or in any other way?

For example, the first application is for event management, and I use it to save some event. The second application is for reminders, which will get data from the other application in order to remind me about the event.

This is just a simple example, not a real scenario.

回答1:

Historically, the iPhone has tried to prevent data sharing between apps. The idea was that if you couldn\'t get at another app\'s data, you couldn\'t do anything bad to that app.

In recent releases of IOS, they\'ve loosened that up a bit. For example, the iOS programming guide now has a section on passing data between apps by having one app claim a certain URL prefix, and then having other apps reference that URL. So, perhaps you set your event app to answer \"event://\" URLs the same way that a webserver answers for \"http://\" URLs.

Apple\'s documentation of that approach is here.

Have a peek under \"Implementing Custom URL Schemes\".



回答2:

In the sandboxed world of iOS development sharing data between applications can prove difficult Since iOS developers can’t share data directly through the file system, they need to find alternate solutions for their applications. Some common solutions include:

  • UIDocumentInteractionController

  • UIActivityViewController

  • Shared Keychain Access

  • Custom URL Scheme

  • Web Service

  • iCloud API


UIDocumentInteractionController:

Allows the user to open a document in any other application that registers as being able to handle a particular document Uniform Type Identifier (UTI).

The UIDocumentInteractionController has been used in the past as a means of opening a document in other applications on the device, for example, opening email attachments from the Mail app.

\"UIDocumentInteractionController\"

Unfortunately, the UIDocumentInteractionController‘s UI displays only six applications.

You cannot guarantee that your application will appear in the list. While the UIDocumentInteractionController has not been deprecated, the UIActivityViewController provides a more flexible replacement as of iOS 6.0.

Availability: iOS 3.2+

Pros:

  • Allows sharing of common data types with a wide array of applications.

Cons:

  • Allows control of the type of data sent to the UIDocumentInteractionController, but not the destinations.

  • Requires additional user interaction.

  • Limited number of data destinations may cause your application not to display in the list.


UIActivityViewController:

Allows the user to perform a number of actions with an array of data.

For example they may print, email, copy, post to social media, or open in another application.

You may create your own UIActivity subclasses to provide custom services to the user.

\"UIActivityController\"

Availability: iOS 6.0+

Pros:

  • Great for sharing common data types with a wide array of applications and social media.

  • Can supply an array of items for application to an activity. Objects should conform to UIActivityItemSource protocol.

  • Has the ability to set excluded activity types.

  • Paging UI allows for more data destinations than UIDocumentInteractionController.

Cons:

  • You must define a custom activity type to restrict “Open In…” destinations of common data types.

  • Requires additional user interaction.


Shared Keychain Access:

Allows you to securely store data to a shared keychain that other applications that are part of a suite of applications can access.

All applications that share keychain access must use the same app ID prefix.

For an example of shared keychain access in action. See Apple’s GenericKeychain sample code.

\"Shared

Availability: iOS 3.0+

Pros:

  • Secure access to data.

Cons:

  • You can only share data between applications that share a common app ID prefix.

  • The Keychain API on the iOS Simulator comes from OS X, which has different API than that of the iOS device.


Custom URL Scheme:

Allows data to pass between applications using simple URLs.

\"Custom

Availability: iOS 3.0+

Pros:

  • No network connection required.
  • Great for small amounts of data that you can easily encode into an escaped, legal URL.

Cons:

  • You must encode data into an escaped legal URL.

    Note: base64 encoding has seen common use turning serializable data into a string value. However, base64 strings may include characters that are invalid for use in URLs. You might consider using base64url. See Base 64 Encoding with URL and Filename Safe Alphabet for more information.


iCloud API:

Everybody knows about what is iCloud,Pros and Cons so no more explanation for that.

But One might ask how it is possible to share data between applications inside a single device there are some workarounds to achieve that.

\"iCloud\"

It\'s possible because the identifier which is used for iCloud is different from bundle identifier so it\'s possible to share images,videos and other documents.

To know more see the discussion on this topic


Web Service:

Sync data through third party (e.g. Dropbox) or custom built web service.

\"web

Availability: iOS 2.0+

Pros:

  • Useful for sharing and otherwise distributing large amounts of data.

Cons:

  • Requires a network connection.
  • Web service implementation overhead.

Reference



回答3:

From iOS 8 I\'ve successfully Access Same folder in using \"App Group Functionality.\" I\'m extending answer of @siejkowski.

Note: It will work from same developer account only.

For that you have to follow below steps.

  1. first Enable \"App Groups\" from your developer account.
  2. Generate Provisioning profile. and use it.

Now You have to create Two Apps. Sample Name

  1. Demo_Share_One
  2. Demo_Share_Two

Now We are copying images from Demo_Share_One to Sharing folder which is created by default when you enable App Groups and run app. and will access all those images from Demo_Share_Two.

You have to Take Group Name which was set to your developer account.lets say group.filesharingdemo.

Add Below method in Both apps to get Relative path of sharing folder url.

- (NSString *) getSharedLocationPath:(NSString *)appGroupName {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *groupContainerURL = [fileManager containerURLForSecurityApplicationGroupIdentifier:appGroupName];
    return [groupContainerURL relativePath];
}

Now we are Copying Images from Bundle from Demo_Share_One

-(IBAction)writeImage:(id)sender
{
    for (int i = 0; i<15; i++) 
    {
        NSString *strSourcePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@\"hd%d\",i+1] ofType:@\"jpg\"];
        NSString *strDestinationPath = [[self getSharedLocationPath:@\"group.filesharingdemo\"] stringByAppendingPathComponent:[NSString stringWithFormat:@\"hd%d\",i+1]] ;

        BOOL filewrite = [[NSFileManager defaultManager]copyItemAtPath:strSourcePath toPath:strDestinationPath error:nil];
        if (filewrite)
            NSLog(@\"File write\");
        else
            NSLog(@\"can not write file\");
    }
}

Now in Demo_Share_Two to access those images

NSString *pathShared = [[self getSharedLocationPath:@\"group.filesharingdemo\"] stringByAppendingPathComponent:[NSString stringWithFormat:@\"hd%d.jpg\",number]];
NSLog(@\"%@\",pathShared);
//BOOL fileExist = [[NSFileManager defaultManager] fileExistsAtPath:pathShared];
imgView.image = [UIImage imageWithContentsOfFile:pathShared];

And Now You will get all images which your write from Demo_Share_One.

So From now onwards if you want to share this folder two your third app. just add that app in your group. So it is too easy to access same elements in Your Multiple apps.

if you will not enable App Groups in your AppID then you will get [self getSharedLocationPath:@\"group.filesharingdemo\"] is null.

Thanks to Apple for Share Elements from your own apps functionality. Happy Coding. :)



回答4:

Since iOS 8 you can easily share data between apps as long as they are in the common App Group.

Apple documentation best explains it in the Extensions context: https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html

Basically, you need to:

  1. Define App Group ID (in Certificates, Identifiers & Profiles section of Member Center for your Apple Developer Program.
  2. Enable App Groups capability specifying the above App Group ID for each app that needs to communicate (cen be done either in Xcode: Target -> Capabilities or at Member Center).
  3. Use one of two APIs for shared container access.

First API is based on NSUserDefaults:

NSString *appGroupId = @\"group.my.group.id\";

NSUserDefaults *myDefaults = [[NSUserDefaults alloc] 
                    initWithSuiteName:appGroupId];

[myDefaults setObject:@\"foo\" forKey:@\"bar\"];

Second API is based on NSFileManager. It\'s simply a shared folder that you can access after obtaining it\'s url:

NSString *appGroupId = @\"group.my.group.id\";

NSURL *sharedFolderURL = [[NSFileManager defaultManager] 
                           containerURLForSecurityApplicationGroupIdentifier:appGroupId];

Anything you put inside myDefaults or the folder pointed by sharedFolderURL will be visible and accessible for all your apps.

In case of folder, please write/read atomically just to ensure no deadlocks are possible.



回答5:

Share data between apps possible? Yes it is!

Use UIPasteBoard available from iOS 3.0, documentation is available here. Apple docs say:

The UIPasteboard class enables an application to share data within the application or with another application using system-wide or application-specific pasteboards.

It is also possible to share data between apps in the keychain, although the data is primarily meant to be passwords and such, anything serializable could be stored. Here is a Stack Overflow question about that.



回答6:

You can use Custom URL scheme to access data from one app to another. Follow below mentioned link for more info -

http://iosdevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html



回答7:

Mention that sharing data between apps via UIPasteBoard only works for apps in the same application group in iOS7. As apples says:

+[UIPasteboard pasteboardWithName:create:] and +[UIPasteboard pasteboardWithUniqueName] now unique the given name to allow only those apps in the same application group to access the pasteboard. If the developer attempts to create a pasteboard with a name that already exists and they are not part of the same app suite, they will get their own unique and private pasteboard. Note that this does not affect the system provided pasteboards, general, and find.



回答8:

You can use https://github.com/burczyk/Camouflage to read and write NSData to iOS Camera Roll as .bmp file and share it between apps :)

Brand new solution!



回答9:

If you don\'t mind hitting the network, you could implement a custom web service to do it, or use some cloud service. iCloud itself will not be of much use here; it only allows you to share data between the same app on different devices. You can read about iCloud here.

Without using the network, you can exploit \"fast app switching\" to transfer a limited amount of data between apps via URL encoding. The actual amount of data transferable I don\'t know, but it would be very limited I\'m sure.

JugsteR and baudot\'s answers are best in this case.



回答10:

No. You would have to use some cloud solution.