CNContact encoding of properties

2019-03-03 16:59发布

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?

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-03-03 17:38

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:")
查看更多
登录 后发表回答