0

I have a v-card string with the first name André and I initialise a CNContact with the v-card.

BEGIN:VCARD

VERSION:2.1

N:Foo;André;;;

FN:André Foo

TEL;CELL:00023 4474848

END:VCARD

I initialise the contact with the raw string like this:

if let data = string.data(using: .utf8) {
    do {
        let contacts = try CNContactVCardSerialization.contacts(with: data)
        let contact = contacts.first
        return contact

    } catch {
        print("Data is not a VCard")
    }
}

But when I print out the raw string of contact.givenName I get:

André

How can I get the proper string of the Contacts framework in iOS?

Nico S.
  • 3,056
  • 1
  • 30
  • 64

1 Answers1

1

You need to add a charset to the vcard fields, it defaults to ASCII.

BEGIN:VCARD

VERSION:2.1

N;CHARSET=UTF-8:Foo;André;;;

FN;CHARSET=UTF-8:André Foo

TEL;CELL:00023 4474848

END:VCARD

If you want to hack around this specific type of error in the vcard then you can inject the charset manually into it:

let fixed = string.replacingOccurrences(of: "\nN:", with: "\nN;CHARSET=UTF-8:").replacingOccurrences(of: "\nFN:", with: "\nFN;CHARSET=UTF-8:")
dan
  • 9,695
  • 1
  • 42
  • 40
  • But what If I can't control the charset? Let's assume I get the vcard from a third party... – Nico S. Sep 18 '17 at 20:37
  • Then the third party needs to fix their vcards. – dan Sep 18 '17 at 20:38
  • This is not useful at all, sorry. If the web was like that, we all should give up right now... – Nico S. Sep 18 '17 at 20:39
  • In some cases it is not possible (fix third parties) due to hardware restriction rules. For example, storing vCard data onto NDEF records, written on NFC-tag. It is too expensive fill each field with messy CHARSET=UTF-8 substring. – A. Petrov Jan 24 '19 at 08:50