2017-08-01 35 views
0

我一直在尝试以通用的方式对对象进行JSON编码/解码Swift的CNContact(我的意思是我想确定在运行时对象拥有哪些属性,我想要硬编码它的属性),但是我没有设法这样做。我的问题是:是否有一种方法可以在Swift 4中实现这种行为,如果是的话,该怎么做?JSON编码/解码一般的Swift CNContact对象

+0

在JSON从联系人添加到多个领域? –

+0

我想序列化和反序列化每个CNContact对象持有的所有属性......是否回答你的问题? – mmarkus

回答

1

否,CNContact根据official documentation并没有改变,所以它不符合Codable协议,这仅仅是一个Encodeable & Decodable typealias。你可以看到目前符合EncodableDecodable的类的列表,并且在这里看到以及CNContact不在其中。

但是,您可以编写CNContact的扩展名,使其符合上述协议。

下面是如何在Swift3中使用JSONSerialization框架编码CNContact对象的示例。请注意,这只是一个示例,所以我没有解析所有可能的字段,并且在此实现中,如果某个值不存在于CNContact对象中,则该关键字在JSON中也不存在。另外,解码器功能没有完全实现,但是如果您检查编码器的工作方式,则可以轻松实现解码器功能。

JSON键的名称也随着结构随意选择,所以你可以改变其中的任何一个。

下面的一段代码是一个完整的工作操场文件,所以如果你愿意,你可以自己测试一下。

import Contacts 

let contact = CNMutableContact() 
contact.birthday = DateComponents(calendar: Calendar.current,year: 1887, month: 1, day: 1) 
contact.contactType = CNContactType.person 
contact.givenName = "John" 
contact.familyName = "Appleseed" 

contact.imageData = Data() // The profile picture as a NSData object 

let homeEmail = CNLabeledValue(label:CNLabelHome, value: NSString(string: "[email protected]")) 
let workEmail = CNLabeledValue(label:CNLabelWork, value: NSString(string: "[email protected]")) 
contact.emailAddresses = [homeEmail, workEmail] 

contact.phoneNumbers = [CNLabeledValue(label:CNLabelPhoneNumberiPhone, value:CNPhoneNumber(stringValue:"(408) 555-0126"))] 

let homeAddress = CNMutablePostalAddress() 
homeAddress.street = "1 Infinite Loop" 
homeAddress.city = "Cupertino" 
homeAddress.state = "CA" 
homeAddress.postalCode = "95014" 
contact.postalAddresses = [CNLabeledValue(label:CNLabelHome, value:homeAddress)] 

func encodeContactToJson(contact: CNContact)->Data?{ 
    var contactDict = [String:Any]() 
    if let birthday = contact.birthday?.date { 
     let df = DateFormatter() 
     df.dateFormat = "yyyy-MM-dd" 
     contactDict["birthday"] = df.string(from: birthday) 
    } 
    contactDict["givenName"] = contact.givenName 
    contactDict["familyName"] = contact.familyName 
    if let imageData = contact.imageData { 
     contactDict["image"] = imageData.base64EncodedString() 
    } 
    if contact.emailAddresses.count > 0 { 
     var emailAddresses = [String:String]() 
     for (index, emailAddress) in contact.emailAddresses.enumerated() { 
      emailAddresses[emailAddress.label ?? "email\(index)"] = (emailAddress.value as String) 
     } 
     contactDict["emailAddresses"] = emailAddresses 
    } 
    if contact.phoneNumbers.count > 0 { 
     var phoneNumbers = [String:String]() 
     for (index, phoneNumber) in contact.phoneNumbers.enumerated() { 
      phoneNumbers[phoneNumber.label ?? "phone\(index)"] = phoneNumber.value.stringValue 
     } 
     contactDict["phoneNumbers"] = phoneNumbers 
    } 
    if contact.postalAddresses.count > 0 { 
     var postalAddresses = [String:String]() 
     for (index, postalAddress) in contact.postalAddresses.enumerated() { 
      postalAddresses[postalAddress.label ?? "postal\(index)"] = (CNPostalAddressFormatter.string(from: postalAddress.value, style: .mailingAddress)) 
     } 
     contactDict["postalAddresses"] = postalAddresses 
    } 
    return try? JSONSerialization.data(withJSONObject: contactDict) 
} 

func decodeContactsJson(jsonData: Data)->CNContact?{ 
    if let jsonDict = (try? JSONSerialization.jsonObject(with: jsonData)) as? [String:Any] { 
     let contact = CNMutableContact() 
     print(jsonDict) 
     return contact as CNContact 
    } else { 
     return nil 
    } 
} 

if let jsonContact = encodeContactToJson(contact: contact) { 
    print(decodeContactsJson(jsonData: jsonContact) ?? "Decoding failed") 
} else { 
    print("Encoding failed") 
} 
+0

非常感谢。我完全没有经历过Swift开发的经验,您能否提供一个CNContact这样的扩展的示例代码? – mmarkus

+0

我目前没有安装Xcode9测试版,所以我无法编译'Swift4'代码,我不想为您提供可能无法编译的代码示例。不过,如果你愿意,我可以给你一个小例子,介绍如何使用'Swift3'中已有的'JSONSerialization'框架来完成它。 –

+0

我真的很感激::) – mmarkus

0

尝试使用简单与联系选择。

func contactViewController(_ viewController: CNContactViewController, didCompleteWith contact: CNContact?) { 

    var name = "" 
    var email = "" 
    var mobile = "" 
    var address = "" 
    var companyname = "" 
    var jobtitle = "" 
    var organization = "" 
    var workaddress = "" 
    var worknumber = "" 
    var personalurl = "" 
    var companyurl = "" 
    var otherurl = "" 
    var othernumber = "" 
    var otheraddress = "" 
    var homeemail = "" 
    var workemail = "" 
    var otheremail = "" 
    var dataAll = NSMutableArray() 

    if contact != nil 
    { 
     dataAll = NSMutableArray() 



     if (contact?.isKeyAvailable(CNContactGivenNameKey))! { 
      let name2 = contact?.familyName 
      name = (contact?.givenName)! + " " + name2! 

      UserDefaults.standard.set(name, forKey: "name") 


     } 



     if (contact?.isKeyAvailable(CNContactOrganizationNameKey))! 
     { 
      companyname = (contact?.organizationName)! 


      //var dic : NSDictionary = [:] 
      if companyname != "" { 
       let dic : [String : AnyObject] = ["name":companyname as AnyObject, 
                "type":"companyname" as AnyObject, 
                "typeof":"companyname" as AnyObject] 
       dataAll.add(dic) 
      } 



     } 

     let designation = contact?.jobTitle 

     if (designation?.isEmpty)! 
     { 

     } 
     else 
     { 
      jobtitle = designation! 
      //let dic : [String : AnyObject] = ["designation":jobtitle as AnyObject] 

      let dic : [String : AnyObject] = ["name":jobtitle as AnyObject, 
               "type":"designation" as AnyObject, 
               "typeof":"designation" as AnyObject 
      ] 
      dataAll.add(dic) 

     } 
     if (contact?.isKeyAvailable(CNContactPhoneNumbersKey))!{ 

      if (contact?.phoneNumbers.count == 0) 
      { 

      } 
      else 
      { 

       for phoneNumber:CNLabeledValue in (contact?.phoneNumbers)! { 
        let number = phoneNumber.value 

        let number2 = number.stringValue 


        let lable :String = CNLabeledValue<NSString>.localizedString(forLabel: phoneNumber.label!) 


        let dic : [String : AnyObject] = ["name":number2 as AnyObject, 
                 "type":lable as AnyObject, 
                 "typeof":"phonenumber" as AnyObject] 


        dataAll.add(dic) 


        if number2 != "" 
        { 

        } 


        if lable == "home" 
        { 
         if number2 == "" 
         { 

         } 
         else 
         { 
          mobile = number.stringValue 


          let number2 = String(mobile.digitsOnly())! 



         } 


        } 
        if lable == "work" 
        { 
         if number2 == "" 
         { 

         } 
         else 
         { 
          worknumber = number.stringValue 

         } 


        } 
        if lable == "mobile" 
        { 
         if number2 == "" 
         { 

         } 
         else 
         { 
          othernumber = number.stringValue 


         } 


        } 

       } 

      } 
     } 


     if (contact?.isKeyAvailable(CNContactEmailAddressesKey))! { 

      if (contact?.emailAddresses.count == 0) 
      { 

      } 
      else 
      { 

       for emaiadd:CNLabeledValue in (contact?.emailAddresses)! { 

        let name2 = (emaiadd.value as String) as String 

        if name2 != "" 
        { 
         UserDefaults.standard.set(emaiadd.value as String, forKey: "mainemail") 
        } 

        let lable :String = CNLabeledValue<NSString>.localizedString(forLabel: emaiadd.label!) 

        // let dic : [String : AnyObject] = [lable:emaiadd.value as String as AnyObject] 
        let dic : [String : AnyObject] = ["name":name2 as AnyObject, 
                 "type":lable as AnyObject, 
                 "typeof":"email" as AnyObject] 

        dataAll.add(dic) 


        if lable == "home" 
        { 

         if name2 == "" 
         { 

         } 
         else 
         { 
          email = emaiadd.value as String 


         } 

        } 
        if lable == "work" 
        { 
         if name2 == "" 
         { 

         } 
         else 
         { 
          workemail = emaiadd.value as String 

         } 

        } 
        if lable == "other" 
        { 
         if name2 == "" 
         { 

         } 
         else 
         { 
          otheremail = emaiadd.value as String 

         } 

        } 

       } 
      } 

     } 



     if (contact?.isKeyAvailable(CNContactPostalAddressesKey))! { 

      for addres:CNLabeledValue in (contact?.postalAddresses)! { 

       let addre = addres.value 
       let addre2 = addre.street 

       let lable :String = CNLabeledValue<NSString>.localizedString(forLabel: addres.label!) 


       let dic : [String : AnyObject] = ["name":addre2 as AnyObject, 
                "type":lable as AnyObject, 
                "typeof":"address" as AnyObject] 

       dataAll.add(dic) 

       if lable == "home" 
       { 
        if addre2 == "" 
        { 

        } 
        else 
        { 
         address = addre.street 



        } 
       } 

       if lable == "work" 
       { 
        if addre2 == "" 
        { 

        } 
        else 
        { 
         workaddress = addre.street 

        } 

       } 
       if lable == "other" 
       { 
        if addre2 == "" 
        { 

        } 
        else 
        { 
         otheraddress = addre.street 


        } 
       } 

       print(lable + (addre.street)) 
      } 


     } 

     if (contact?.isKeyAvailable(CNContactUrlAddressesKey))! { 

      for urladd:CNLabeledValue in (contact?.urlAddresses)! { 

       let url2 = (urladd.value as String) as String 

       let lable :String = CNLabeledValue<NSString>.localizedString(forLabel: urladd.label!) 


       let dic : [String : AnyObject] = ["name":url2 as AnyObject, 
                "type":lable as AnyObject, 
                "typeof":"url" as AnyObject] 

       dataAll.add(dic) 

       if lable == "home" 
       { 
        if url2 == "" 
        { 

        } 
        else 
        { 
         personalurl = urladd.value as String 



        } 
       } 
       if lable == "work" 
       { 
        if url2 == "" 
        { 

        } 
        else 
        { 
         companyurl = urladd.value as String 


        } 

       } 
       if lable == "other" 
       { 
        if url2 == "" 
        { 

        } 
        else 
        { 
         otherurl = urladd.value as String 



        } 

       } 


      } 

     } 

     if (contact?.isKeyAvailable(CNContactImageDataKey))! { 

      let image = contact?.imageData 

      let utf8str = image?.base64EncodedString() 


     } 



     dataArr = [["code": "Mobile", "title": othernumber],["code": "Work Number", "title": worknumber],["code": "OtherMobile", "title": number2],["code": "Email", "title": email],["code": "WorkEmail", "title": workemail],["code": "OtherEmail", "title": otheremail],["code": "Address", "title": address],["code": "Work Address", "title": workaddress],["code": "OtherAddress", "title": otheraddress],["code": "Company Name", "title": companyname],["code": "Designation", "title": jobtitle],["code": "Personal Website", "title": personalurl],["code": "Company Website", "title": companyurl],["code": "Other Website", "title": otherurl]] 
    } 

} 

这个代码在按钮动作你要

let contactPickerViewController = CNContactPickerViewController() 

     contactPickerViewController.delegate = self 

     present(contactPickerViewController, animated: true, completion: nil) 
+0

如果可能的话,在使用Swift的时候,避免使用具有原生Swift替代品的基础版本的数据结构(例如'NSMutableArray',你应该使用'Array ')。此外,您应该重新格式化您的代码,因为使用所有不必要的空格来阅读是非常困难的。你的回答实际上并没有回答这个问题,因为你只返回一个字典,而不是实际的'JSON'对象,并且在这个问题中没有提及'CNContactPickerViewController'。 –