在两个iOS应用之间传递自定义对象

问题描述:

我需要一些帮助。我的帐户下有两个应用程序。在两个iOS应用之间传递自定义对象

我需要将自定义对象从应用程序A传递给应用程序B.如何使用应用程序组来执行此操作?

我看到使用URL方案是一种古老的做法。

那么传递数据两个应用程序的最新方式是什么?

+0

'1与您的模型来创建自己的框架。 UIPasteboard','2.AirDrop','3。 URL Scheme','4。应用程序扩展程序https://lionhylra.wordpress.com/2015/09/17/inter-app-communication-in-ios/ – TonyMkenu

+0

如果您的应用程序在同一个应用程序组中,则可以在应用程序之间共享数据(iOS8 +) http://*.com/questions/9425706/share-data-between-two-or-more-iphone-applications –

在App A(保存对象)

  1. 在功能,点击 “+” 添加一个应用程序组 enter image description here

  2. 在你的对象类,则需要延长你想分享的课程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. 保存数据从您的应用

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

在你的应用B(GET对象)

  1. 添加相同的应用程序组作为应用程序A(见1.1 )

  2. 在视图控制器中,您想获取应用程序A对象:

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

请注意,您必须实现文件在您的Person类,最好的做法是在它