Question?
Reading the title, everyone must have guessed the problem they want to mention. That is sharing some data stored in App over another App with UserDefaults. This technique is not too new at this time.
Specifically, you have also seen, many applications have applied, may not use this method but will also use another method.
Some applications have been implemented:
How to do that?
The first release of the iOS SDK made it possible to do that. That is UserDefault
. Perhaps many of you think that UserDefault is only used to store some information in the App. And yes, at first glance, I think UserDefault can only do that.
But no, UserDefault does more than that, in addition to storage, you can also share information between Apps.
Share data in an app group
For more, check out: Apple Documentation
How to use App Groups: https://github.com/pgpt10/Today-Widget
Create App Group
Go to the Target section of the project, under Signing & Capabilities. Let’s add the App Group
Suite Name
1 2 3 4 5 6 | extension UserDefaults { static var shared: UserDefaults? { return UserDefaults(suiteName: "___ Chính Group Name ___") } } |
Use UserDefaults
• Save values
1 2 3 4 5 6 | if let userDefaults = UserDefaults.shared { userDefaults.set("test 1" as AnyObject, forKey: "key1") userDefaults.set("test 2" as AnyObject, forKey: "key2") userDefaults.synchronize() } |
• Get value
1 2 3 4 5 | if let userDefaults = UserDefaults.shared { let value1 = userDefaults.string(forKey: "key1") let value2 = userDefaults.string(forKey: "key2") } |
App screen
I have written 2 simple applications that use the same group name to share data through User Default.
Application 1: There is simply one button, when tapping the button increases the count.
Application 2: Display the number taped in application 1.
And here are the results.
Conclusion
From the idea above, we can do many more things. Hope a simple article, making it easier for everyone to understand.