在UserDefaults中保存CNContact

时间:2017-10-31 04:59:08

标签: ios swift nsuserdefaults cncontact

我试图将CNContact详细信息保存到我的UserDefaults中,但它失败了。 我可以保存CNContact的任何其他方式吗?

struct User {
    var firstName: String = ""
    var lastName: String = ""
    var email: String = ""
    var phoneNumber: String = ""
    var company: String = ""
    var assistantContact: CNContact?

    init(firstName: String, lastName: String, email: String, phoneNumber: String, company: String, assistantContact: CNContact? = nil) {
        self.firstName = firstName
        self.lastName = lastName
        self.email = email
        self.phoneNumber = phoneNumber
        self.company = company
        self.assistantContact = assistantContact
    }

    func encode() -> Dictionary<String, AnyObject> {

        var dictionary : Dictionary = Dictionary<String, AnyObject>()
        dictionary["firstName"] = firstName as AnyObject?
        dictionary["lastName"] = lastName as AnyObject?
        dictionary["email"] = email as AnyObject?
        dictionary["phoneNumber"] = phoneNumber as AnyObject?
        dictionary["company"] = company as AnyObject?
        dictionary["assistantContact"] = assistantContact as AnyObject?
        return dictionary

    }

    init(dictionary: Dictionary<String, AnyObject>) {
        if let firstName = dictionary["firstName"] as? String {
            self.firstName = firstName
        }
        if let lastName = dictionary["lastName"] as? String {
            self.lastName = lastName
        }
        if let email = dictionary["email"] as? String {
            self.email = email
        }
        if let phoneNumber = dictionary["phoneNumber"] as? String {
            self.phoneNumber = phoneNumber
        }
        if let company = dictionary["company"] as? String {
            self.company = company
        }
        if let assistantContact = dictionary["assistantContact"] as? CNContact {
            self.assistantContact = assistantContact
        }
    }

}

1 个答案:

答案 0 :(得分:0)

首先使用编码联系人数组。

let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: contactsArray)

现在将encodedData保存在UserDefaults中。

对于解码联系人数组,

if let contacts: [CNContact] = decodedData as? [CNContact] {
            //Decoded Contacts Array
 }