Sunday 23 April 2017

Share Data between app and share extension in iOS

App extension provide  a way to perform core functionality of the app, from the activity view controller. For example , if we are seeing an photo in Photos app, then if we want to share this photo on Facebook, we can open it with  Facebook by choosing Facebook form the default activity view controller of the Apple. 
We can also list our app in the default list of the sharing app in activity view controller provided by the Apple by default.
I am not discussing the fundamental of how to create a share extension in iOS app. Today I am going to discuss how to share the data between app and share extension. 

Because iOS app is sandboxed, so to  have common access to data between two targets, we have to create a shared container, in which both targets have read/write access.

1) To create a shared container, enable the group service for the app from the Xcode setting and give the name of group in reversed domain. example: group.appIdentfier

2) Now also enable the group service for the extension target. Here don't create an another group, just choose the group we have created last.

3) Now switch to developer account and create separate provisioning profiles for app and share extension with group configured.

Now we have a shared container, so to have common access to data(like login preferences ) in both targets(app and share extension) we can store these kinds of data in shared UserDefaults. 

Write data in shared UserDefaults: 
if let defaults = UserDefaults.init(suiteName:
        "sharedGroupName"){
        //read and write to UserDefaults       
        }


To read and write files into shared document directory, get the url of document directory and perform task, which is similar to as we do with default file manager.

if let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: AppConstants.kSharedGroupName){
 }

Here url is the path of the document directory, You can create file and folder at this path.

        





8 comments:

  1. Hai Good information shared about IOS. Keep sharing updated ios tutorials. This blog post is really helpful.

    ReplyDelete
  2. hello, can you upload full demo of ios share extension open containing app (Swift )

    ReplyDelete
  3. Thanks for provide great Information and looking beautiful blog, really nice required information & the things. I never imagined and i would request, right more blog and blog post like that for us. Thanks you once again
    Java Training in Chennai

    Java Training in Velachery

    Java Training in Tambaram

    Java Training in Porur

    Java Training in OMR

    Java Training in Annanagar

    ReplyDelete