Passing custom objects between two iOS Apps

2019-09-03 12:34发布

问题:

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 ?

回答1:

IN YOUR APP A (SAVE OBJECT)

  1. Under capabilities, Click "+" to add an App Group

  2. 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")
        }
    }
    
  3. 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)

  1. Add the same app group as the App A (see 1.1)

  2. 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