I have a task to share data between apps in the same device. May be both apps can use a shared database on same device. How to share Data between two apps in IOS. Anybody have done it in any way. Please let me know. Thanks
Asked
Active
Viewed 9,239 times
22
-
Check out [this link](http://www.enharmonichq.com/sharing-data-locally-between-ios-apps/). It is based in Objective-C but the same concept still applies. – Matt Le Fleur Sep 18 '15 at 13:08
-
@Phoen1xUK I think that article is obsolete, since iOS 8, App groups are the official way to do it. – neuhaus Sep 18 '15 at 13:12
-
I am talking about App groups. have you implemented this? – Abhishek Sep 18 '15 at 13:12
1 Answers
32
You can turn on App group on your App Project capabilities tab on both of your apps with the same group container ID. "group.com.yourCompanyID.sharedDefaults"
Then you can access the same folder from your apps using the following url:
let sharedContainerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.yourCompanyID.sharedDefaults")!
So if you would like to share a switch state from two different apps you should do it as follow:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var sharedSwitch: UISwitch!
let switchURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.yourCompanyID.sharedDefaults")!
.appendingPathComponent("switchState.plist")
override func viewDidLoad() {
super.viewDidLoad()
print(switchURL.path)
NotificationCenter.default.addObserver(self, selector: #selector(updateSwitch), name: .UIApplicationDidBecomeActive, object: nil)
}
func updateSwitch(_ notofication: Notification) {
sharedSwitch.isOn = NSKeyedUnarchiver.unarchiveObject(withFile: switchURL.path) as? Bool == true
}
@IBAction func switched(_ sender: UISwitch) {
let success = NSKeyedArchiver.archiveRootObject(sender.isOn, toFile: switchURL.path)
print(success)
}
}

Leo Dabus
- 229,809
- 59
- 489
- 571