在两个iOS应用程序之间传递自定义对象 [英] Passing custom objects between two iOS Apps

查看:189
本文介绍了在两个iOS应用程序之间传递自定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助。我的帐户下有两个应用程序。

I need some help on something. I have two apps under my account.

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

I need to pass a custom object from App A to App B. How can I do this using app groups ?

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

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. 在功能下,单击+到添加应用程序组

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

在对象类中,您需要扩展所需的类分享到 NSObject NSCoding

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


  • 从应用A保存数据

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


  • 在您的应用程序B中(获取对象)


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

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

    在View控制器中你想获得App A对象:

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


    请注意,您需要在两个文件中实现Person类,最佳做法是使用您的模型创建自己的框架

    这篇关于在两个iOS应用程序之间传递自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆