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)
}
}