I need some help on something. I have two apps under my account.
I need to pass a custom object from App A to App B. How can I do this using app groups ?
I saw that using URL schemes is a old a way of doing it.
So what is the newest way of passing data two apps ?
IN YOUR APP A (SAVE OBJECT)
Under capabilities, Click "+" to add an App Group
In your Object Class, you need to extend the class you want to share to NSObject and NSCoding
class Person : NSObject, NSCoding {
var nom: String
var prenom: String
required init(name: String, prenom: String) {
self.nom = name
self.prenom = prenom
}
required init(coder decoder: NSCoder) {
self.nom = decoder.decodeObject(forKey: "name") as? String ?? ""
self.prenom = decoder.decodeObject(forKey: "prenom") as? String ?? ""
}
func encode(with coder: NSCoder) {
coder.encode(nom, forKey: "nom")
coder.encode(prenom, forKey: "prenom")
}
}
Save Data from your App A
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let person = Person(name: "Ugo", prenom: "Marinelli")
saveData(person: person)
}
func saveData(person : Person){
//Map Class to recognize it
NSKeyedArchiver.setClassName("Person", for: Person.self)
//Encode the object
let personEncoded = NSKeyedArchiver.archivedData(withRootObject: person)
//Push the object to the App Group
UserDefaults(suiteName: "group.tag.testAppGroup")!.set(personEncoded, forKey: "FirstLaunch")
}
IN YOUR APP B (GET OBJECT)
Add the same app group as the App A (see 1.1)
In the View controller you want to get the App A object :
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Class Mapping
NSKeyedUnarchiver.setClass(Person.self, forClassName: "Person")
//Get The encoded data from App Group
let personEncoded = UserDefaults(suiteName: "group.tag.testAppGroup")!.object(forKey: "FirstLaunch") as! NSData
//Decode to get our Person object
let personDecoded = NSKeyedUnarchiver.unarchiveObject(with: personEncoded as Data) as? Person
print(personDecoded?.prenom)
}
Note that you need to implement your Person class in both file, the best practice would be to create your own framework with your model in it