ChatGPT解决这个技术问题 Extra ChatGPT

Share data between two or more iPhone applications

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.


C
Community

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.

https://i.stack.imgur.com/MAuqD.jpg

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.

https://i.stack.imgur.com/Mio38.jpg

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.

https://i.stack.imgur.com/WiCke.png

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.

https://i.stack.imgur.com/bv4X9.png

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.

https://i.stack.imgur.com/Q4Gyi.jpg

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.

https://i.stack.imgur.com/p4gPZ.jpg

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


like the extensive answer and use of graphics
You should mention UIPasteboard API as well.
@EvgenyKarkan - Please feel free to edit the post :)
C
ChintaN -Maddy- Ramani

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.

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

Now You have to create Two Apps. Sample Name

Demo_Share_One 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. :)


s/getSharedLocationPath:/sharedLocationPathForAppGroup:/ :-)
@ChintaN -Maddy- Ramani can the shared location path contain an sqlLite or realm db? Would extensions be needed for this?
@user2363025 Maybe yes. You can try. I just tried with images. maybe you can copy database there.
@ChintaN-Maddy-Ramani. I am getting below error: Domain=NSCocoaErrorDomain Code=512 "The file “1FAA9B86-E775-4A2D-A2D6-A442C8A9A8FA” couldn’t be saved in the folder “AppGroup”." UserInfo={NSFilePath=/private/var/mobile/Containers/Shared/AppGroup/1FAA9B86-E775-4A2D-A2D6-A442C8A9A8FA, NSUnderlyingError=0x282202250 {Error Domain=NSPOSIXErrorDomain Code=21 "Is a directory"}}
A
AlexVogel

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".


Thanks this was the exactly i am looking for.
Can large data be shared that way, for example files?
If you're reading this far, make sure you check @siejkowski response below, as it is more up-to-date.
The response from @chintan-maddy-ramani is worthy of note also.
Yes, there have been many better ways added since I wrote this response. Old question has old answer!
s
siejkowski

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:

Define App Group ID (in Certificates, Identifiers & Profiles section of Member Center for your Apple Developer Program. 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). 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.


i gone through your steps and get shared url. but how to put Image on that path. i append my image name and write data. then i try to retrieve but could not get image back.
i have successfully did it write all images from app1 and retrieve all images from app2 using app group. Thanks . +1 :).
Can I have a third party app join my group (by choice), or do all apps have to be from the same developer account?
@DwarDoh it has to be from same developer account.
C
Community

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.


Great! This looks like a viable way to share data between apps.
The UIPasteboard sounds like a good solution for sharing small data, like copy pasting strings. Is there an option to share files between apps?
@AlikElzin-kilaka yes, it supports NSData as well.
C
Cœur

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


"Access data" here is misleading. The link refers to an article where some parameters are passed to an app in the URL itself.
M
MasterBeta

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.


What do Apple mean by the "same application group"?
@MagicBulletDave Apps that have the same Bundle Seed ID.
The UIPasteboard class enables an app to share data within the app and with another app. To share data with any other app, you can use system-wide pasteboards; to share data with another app that has the same team ID as your app, you can use app-specific pasteboards.
Q
QED

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.


Hi psoft can you brief more on iCloud sharing which you have explained here in two lines
I read that the iCloud ID doesn't has to match the Bundle ID of the app and therefore iCloud sharing would be an option.
It's possible to transfer 64kB of data inside a standard URL. It actually works well. If you don't have too much data, you can encrypt/base64 for better security.
K
Kamil

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!


creative idea... nice
d
dbrajkovic

No. You would have to use some cloud solution.


As far as I know iCloud is meant for Syncing a data on one device with other devices.If you know any ways to share the data between apps in a device kindly share it.
dbarjkovic you are right we could use cloud solution to sync data between apps as the identifier used for iCloud is different from bundle identifier and its entirely possible. here is a link to verify that stackoverflow.com/a/8882763/730807. upvote for your answer.
Why this answer is downvoted ? This is correct answer but it needs to have more details from the documentation and give some examples