@capacitor/contacts 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,257 @@
1
+ import Contacts
2
+ import Foundation
3
+
4
+ /// Business logic for reading, searching, saving and removing device
5
+ /// contacts via the Contacts framework (`CNContactStore`). Holds no
6
+ /// bridge-framework types; the bridge plugin parses calls and delegates here.
7
+ @objc public class Contacts: NSObject {
8
+
9
+ private let store = CNContactStore()
10
+
11
+ /// Marker value used by the legacy API to request every field.
12
+ private let allFields = "*"
13
+
14
+ // MARK: - Authorization
15
+
16
+ /// `true` for full access, or for iOS 18+ Limited Access (`.limited`),
17
+ /// which the store serves transparently against the user-selected subset
18
+ /// for both reads and writes.
19
+ @objc public func isAuthorized() -> Bool {
20
+ let status = CNContactStore.authorizationStatus(for: .contacts)
21
+ if status == .authorized { return true }
22
+ if #available(iOS 18.0, *), status == .limited { return true }
23
+ return false
24
+ }
25
+
26
+ /// Requests contacts access. The completion receives whether access was
27
+ /// granted; on iOS 18+ choosing "Select Contacts…" (Limited Access)
28
+ /// completes with `true`.
29
+ @objc public func requestAccess(completion: @escaping (Bool) -> Void) {
30
+ store.requestAccess(for: .contacts) { granted, _ in
31
+ completion(granted || self.isAuthorized())
32
+ }
33
+ }
34
+
35
+ // MARK: - Keys
36
+
37
+ /// Keys fetched from the store. Image data is by far the heaviest key,
38
+ /// so bulk searches fetch only the thumbnail; single-contact fetches add
39
+ /// the full image as a fallback for contacts without a generated thumbnail.
40
+ private func fetchKeys(includePhotos: Bool, fullPhotoData: Bool = false) -> [CNKeyDescriptor] {
41
+ var stringKeys = [
42
+ CNContactIdentifierKey,
43
+ CNContactGivenNameKey,
44
+ CNContactFamilyNameKey,
45
+ CNContactMiddleNameKey,
46
+ CNContactNamePrefixKey,
47
+ CNContactNameSuffixKey,
48
+ CNContactNicknameKey,
49
+ CNContactOrganizationNameKey,
50
+ CNContactDepartmentNameKey,
51
+ CNContactJobTitleKey,
52
+ CNContactPhoneNumbersKey,
53
+ CNContactEmailAddressesKey,
54
+ CNContactPostalAddressesKey,
55
+ CNContactUrlAddressesKey,
56
+ CNContactInstantMessageAddressesKey,
57
+ CNContactBirthdayKey
58
+ // NOTE: CNContactNoteKey is intentionally omitted. Since iOS 13 it
59
+ // requires the restricted `com.apple.developer.contacts.notes`
60
+ // entitlement (granted by Apple on request); requesting it without
61
+ // the entitlement makes every fetch throw. `note` is therefore
62
+ // not supported on iOS by default; see README.
63
+ ]
64
+ if includePhotos {
65
+ stringKeys.append(CNContactThumbnailImageDataKey)
66
+ if fullPhotoData {
67
+ stringKeys.append(CNContactImageDataKey)
68
+ }
69
+ }
70
+ var keys = stringKeys.map { $0 as CNKeyDescriptor }
71
+ keys.append(CNContactFormatter.descriptorForRequiredKeys(for: .fullName))
72
+ return keys
73
+ }
74
+
75
+ // MARK: - Search
76
+
77
+ /// Searches contacts and returns an array of wire-format dictionaries.
78
+ /// Under iOS 18+ Limited Access the store enumerates only the contacts
79
+ /// the user shared with the app.
80
+ ///
81
+ /// - Parameters:
82
+ /// - fields: fields to search against (`["*"]` for all).
83
+ /// - filter: case-insensitive substring; empty returns all.
84
+ /// - multiple: when false, at most one contact is returned.
85
+ /// - desiredFields: if non-empty, limits the fields populated on results.
86
+ /// - hasPhoneNumber: when true, only contacts with a phone number are kept.
87
+ public func search(
88
+ fields: [String],
89
+ filter: String,
90
+ multiple: Bool,
91
+ desiredFields: [String],
92
+ hasPhoneNumber: Bool
93
+ ) throws -> [[String: Any]] {
94
+ let desired = Set(desiredFields)
95
+ let wantsPhotos = desired.isEmpty || desired.contains("photos")
96
+ let request = CNContactFetchRequest(keysToFetch: fetchKeys(includePhotos: wantsPhotos))
97
+ let needle = filter.lowercased()
98
+
99
+ var results: [[String: Any]] = []
100
+
101
+ do {
102
+ try store.enumerateContacts(with: request) { contact, stopPointer in
103
+ if hasPhoneNumber && contact.phoneNumbers.isEmpty { return }
104
+
105
+ if !filter.isEmpty && !self.contactMatches(contact, fields: fields, needle: needle) {
106
+ return
107
+ }
108
+
109
+ results.append(self.contactToDictionary(contact, desiredFields: desired))
110
+
111
+ if !multiple {
112
+ stopPointer.pointee = true
113
+ }
114
+ }
115
+ } catch {
116
+ throw mapStoreError(error)
117
+ }
118
+
119
+ return results
120
+ }
121
+
122
+ /// `true` when any of the requested `fields` of `contact` contains
123
+ /// `needle` (case-insensitive). `["*"]` searches every field, mirroring
124
+ /// the legacy field-restricted search semantics.
125
+ private func contactMatches(_ contact: CNContact, fields: [String], needle: String) -> Bool {
126
+ let searchAll = fields.contains(allFields)
127
+ let requested = Set(fields)
128
+ func wants(_ candidates: String...) -> Bool {
129
+ return searchAll || !requested.isDisjoint(with: candidates)
130
+ }
131
+
132
+ if wants("id") && contact.identifier.lowercased() == needle {
133
+ return true
134
+ }
135
+
136
+ var haystacks: [String] = []
137
+ if wants("displayName", "name", "formatted") {
138
+ haystacks.append(CNContactFormatter.string(from: contact, style: .fullName) ?? "")
139
+ }
140
+ if wants("name", "givenName") { haystacks.append(contact.givenName) }
141
+ if wants("name", "familyName") { haystacks.append(contact.familyName) }
142
+ if wants("name", "middleName") { haystacks.append(contact.middleName) }
143
+ if wants("name", "honorificPrefix") { haystacks.append(contact.namePrefix) }
144
+ if wants("name", "honorificSuffix") { haystacks.append(contact.nameSuffix) }
145
+ if wants("nickname") { haystacks.append(contact.nickname) }
146
+ if wants("organizations", "department", "title") {
147
+ haystacks.append(contentsOf: [contact.organizationName, contact.departmentName, contact.jobTitle])
148
+ }
149
+ if wants("phoneNumbers") {
150
+ haystacks.append(contentsOf: contact.phoneNumbers.map { $0.value.stringValue })
151
+ }
152
+ if wants("emails") {
153
+ haystacks.append(contentsOf: contact.emailAddresses.map { $0.value as String })
154
+ }
155
+ if wants("urls") {
156
+ haystacks.append(contentsOf: contact.urlAddresses.map { $0.value as String })
157
+ }
158
+ if wants("ims") {
159
+ haystacks.append(contentsOf: contact.instantMessageAddresses.map { $0.value.username })
160
+ }
161
+ if wants("addresses", "streetAddress", "locality", "region", "postalCode", "country") {
162
+ for labeled in contact.postalAddresses {
163
+ let postal = labeled.value
164
+ haystacks.append(contentsOf: [postal.street, postal.city, postal.state, postal.postalCode, postal.country])
165
+ }
166
+ }
167
+
168
+ return haystacks.contains { $0.lowercased().contains(needle) }
169
+ }
170
+
171
+ // MARK: - Read single
172
+
173
+ /// Returns the wire-format dictionary for the contact identified by
174
+ /// `identifier`, or nil if not found (or outside the Limited Access set).
175
+ public func getContact(byId identifier: String, desiredFields: [String] = []) -> [String: Any]? {
176
+ do {
177
+ let contact = try store.unifiedContact(withIdentifier: identifier, keysToFetch: fetchKeys(includePhotos: true, fullPhotoData: true))
178
+ return contactToDictionary(contact, desiredFields: Set(desiredFields))
179
+ } catch {
180
+ return nil
181
+ }
182
+ }
183
+
184
+ // MARK: - Save (insert or update)
185
+
186
+ /// Inserts a new contact or updates the existing one identified by
187
+ /// `contact["id"]`. Returns the saved contact's wire-format dictionary.
188
+ ///
189
+ /// Under iOS 18+ Limited Access, inserted contacts join the app's
190
+ /// accessible set automatically; updating a contact outside that set
191
+ /// throws `.invalidArgument` (the store cannot see it).
192
+ public func save(contact dict: [String: Any]) throws -> [String: Any] {
193
+ let saveRequest = CNSaveRequest()
194
+ let identifier = (dict["id"] as? String)?.isEmpty == false ? dict["id"] as? String : nil
195
+
196
+ let mutable: CNMutableContact
197
+ if let identifier = identifier {
198
+ let keys = fetchKeys(includePhotos: true, fullPhotoData: true)
199
+ guard let existing = try? store.unifiedContact(withIdentifier: identifier, keysToFetch: keys),
200
+ let copy = existing.mutableCopy() as? CNMutableContact else {
201
+ throw ContactsError.invalidArgument
202
+ }
203
+ mutable = copy
204
+ apply(dict, to: mutable)
205
+ saveRequest.update(mutable)
206
+ } else {
207
+ mutable = CNMutableContact()
208
+ apply(dict, to: mutable)
209
+ saveRequest.add(mutable, toContainerWithIdentifier: nil)
210
+ }
211
+
212
+ do {
213
+ try store.execute(saveRequest)
214
+ } catch {
215
+ throw mapStoreError(error)
216
+ }
217
+
218
+ guard let saved = getContact(byId: mutable.identifier) else {
219
+ throw ContactsError.unknown
220
+ }
221
+ return saved
222
+ }
223
+
224
+ // MARK: - Remove
225
+
226
+ /// Removes the contact identified by `identifier`. Throws
227
+ /// `.invalidArgument` when no accessible contact has that id.
228
+ public func remove(id identifier: String) throws {
229
+ guard let contact = try? store.unifiedContact(withIdentifier: identifier, keysToFetch: [CNContactIdentifierKey as CNKeyDescriptor]),
230
+ let mutable = contact.mutableCopy() as? CNMutableContact else {
231
+ throw ContactsError.invalidArgument
232
+ }
233
+ let request = CNSaveRequest()
234
+ request.delete(mutable)
235
+ do {
236
+ try store.execute(request)
237
+ } catch {
238
+ throw mapStoreError(error)
239
+ }
240
+ }
241
+
242
+ // MARK: - Error mapping
243
+
244
+ /// Maps Contacts-framework errors onto the unified error codes.
245
+ private func mapStoreError(_ error: Error) -> ContactsError {
246
+ let nsError = error as NSError
247
+ guard nsError.domain == CNErrorDomain else { return .ioError }
248
+ switch nsError.code {
249
+ case CNError.Code.authorizationDenied.rawValue:
250
+ return .permissionDenied
251
+ case CNError.Code.recordDoesNotExist.rawValue:
252
+ return .invalidArgument
253
+ default:
254
+ return .ioError
255
+ }
256
+ }
257
+ }
@@ -0,0 +1,43 @@
1
+ import Foundation
2
+
3
+ /// OutSystems unified error codes for the Contacts plugin, in the
4
+ /// `OS-PLUG-CONT-NNNN` format. The numeric suffix mirrors the legacy Cordova
5
+ /// `ContactError` codes so both stacks report equivalent failures.
6
+ public enum ContactsError: Error {
7
+ case unknown
8
+ case invalidArgument
9
+ case timeout
10
+ case pendingOperation
11
+ case ioError
12
+ case notSupported
13
+ case operationCancelled
14
+ case permissionDenied
15
+
16
+ /// The `OS-PLUG-CONT-NNNN` code carried on `call.reject`.
17
+ public var code: String {
18
+ switch self {
19
+ case .unknown: return "OS-PLUG-CONT-0000"
20
+ case .invalidArgument: return "OS-PLUG-CONT-0001"
21
+ case .timeout: return "OS-PLUG-CONT-0002"
22
+ case .pendingOperation: return "OS-PLUG-CONT-0003"
23
+ case .ioError: return "OS-PLUG-CONT-0004"
24
+ case .notSupported: return "OS-PLUG-CONT-0005"
25
+ case .operationCancelled: return "OS-PLUG-CONT-0006"
26
+ case .permissionDenied: return "OS-PLUG-CONT-0020"
27
+ }
28
+ }
29
+
30
+ /// Human-readable message paired with the code.
31
+ public var message: String {
32
+ switch self {
33
+ case .unknown: return "An unknown error occurred."
34
+ case .invalidArgument: return "Invalid arguments were provided."
35
+ case .timeout: return "The operation timed out."
36
+ case .pendingOperation: return "A pending operation is already in progress."
37
+ case .ioError: return "An I/O error occurred while accessing contacts."
38
+ case .notSupported: return "The operation is not supported on this device."
39
+ case .operationCancelled: return "The operation was cancelled."
40
+ case .permissionDenied: return "Contacts permission was denied."
41
+ }
42
+ }
43
+ }
@@ -0,0 +1,310 @@
1
+ import Contacts
2
+ import Foundation
3
+
4
+ /// Converts between `CNContact` and the W3C-style contact dictionaries the
5
+ /// plugin returns and accepts; shared by every method result and `save` input.
6
+ extension Contacts {
7
+
8
+ // MARK: - Mapping CNContact -> dictionary
9
+
10
+ private func wants(_ field: String, _ desired: Set<String>) -> Bool {
11
+ return desired.isEmpty || desired.contains(field)
12
+ }
13
+
14
+ /// Maps a `CNContact` to a contact dictionary. Every property is guarded with
15
+ /// `isKeyAvailable` so partially-fetched contacts (e.g. returned by the
16
+ /// permissionless system picker) never raise
17
+ /// `CNContactPropertyNotFetchedException`.
18
+ func contactToDictionary(_ contact: CNContact, desiredFields desired: Set<String>) -> [String: Any] {
19
+ var dict: [String: Any] = [:]
20
+ dict["id"] = contact.identifier
21
+
22
+ let formattedName = contact.areKeysAvailable([CNContactFormatter.descriptorForRequiredKeys(for: .fullName)])
23
+ ? (CNContactFormatter.string(from: contact, style: .fullName) ?? "")
24
+ : ""
25
+
26
+ if wants("displayName", desired) {
27
+ dict["displayName"] = formattedName
28
+ }
29
+
30
+ if wants("name", desired) {
31
+ var name: [String: Any] = [:]
32
+ name["formatted"] = formattedName
33
+ if contact.isKeyAvailable(CNContactFamilyNameKey) { name["familyName"] = contact.familyName }
34
+ if contact.isKeyAvailable(CNContactGivenNameKey) { name["givenName"] = contact.givenName }
35
+ if contact.isKeyAvailable(CNContactMiddleNameKey) { name["middleName"] = contact.middleName }
36
+ if contact.isKeyAvailable(CNContactNamePrefixKey) { name["honorificPrefix"] = contact.namePrefix }
37
+ if contact.isKeyAvailable(CNContactNameSuffixKey) { name["honorificSuffix"] = contact.nameSuffix }
38
+ dict["name"] = name
39
+ }
40
+
41
+ if wants("nickname", desired) && contact.isKeyAvailable(CNContactNicknameKey) && !contact.nickname.isEmpty {
42
+ dict["nickname"] = contact.nickname
43
+ }
44
+
45
+ if wants("phoneNumbers", desired) && contact.isKeyAvailable(CNContactPhoneNumbersKey) && !contact.phoneNumbers.isEmpty {
46
+ dict["phoneNumbers"] = contact.phoneNumbers.map { labeled in
47
+ field(
48
+ id: labeled.identifier,
49
+ value: labeled.value.stringValue,
50
+ type: canonicalLabel(labeled.label)
51
+ )
52
+ }
53
+ }
54
+
55
+ if wants("emails", desired) && contact.isKeyAvailable(CNContactEmailAddressesKey) && !contact.emailAddresses.isEmpty {
56
+ dict["emails"] = contact.emailAddresses.map { labeled in
57
+ field(
58
+ id: labeled.identifier,
59
+ value: labeled.value as String,
60
+ type: canonicalLabel(labeled.label)
61
+ )
62
+ }
63
+ }
64
+
65
+ if wants("urls", desired) && contact.isKeyAvailable(CNContactUrlAddressesKey) && !contact.urlAddresses.isEmpty {
66
+ dict["urls"] = contact.urlAddresses.map { labeled in
67
+ field(
68
+ id: labeled.identifier,
69
+ value: labeled.value as String,
70
+ type: canonicalLabel(labeled.label)
71
+ )
72
+ }
73
+ }
74
+
75
+ if wants("ims", desired) && contact.isKeyAvailable(CNContactInstantMessageAddressesKey) && !contact.instantMessageAddresses.isEmpty {
76
+ dict["ims"] = contact.instantMessageAddresses.map { labeled in
77
+ field(
78
+ id: labeled.identifier,
79
+ value: labeled.value.username,
80
+ type: labeled.value.service.lowercased()
81
+ )
82
+ }
83
+ }
84
+
85
+ if wants("addresses", desired) && contact.isKeyAvailable(CNContactPostalAddressesKey) && !contact.postalAddresses.isEmpty {
86
+ dict["addresses"] = contact.postalAddresses.map(addressDictionary)
87
+ }
88
+
89
+ let hasOrgKeys = contact.isKeyAvailable(CNContactOrganizationNameKey) &&
90
+ contact.isKeyAvailable(CNContactDepartmentNameKey) &&
91
+ contact.isKeyAvailable(CNContactJobTitleKey)
92
+ if wants("organizations", desired) && hasOrgKeys &&
93
+ (!contact.organizationName.isEmpty || !contact.departmentName.isEmpty || !contact.jobTitle.isEmpty) {
94
+ dict["organizations"] = [[
95
+ "pref": false,
96
+ "type": "work",
97
+ "name": contact.organizationName,
98
+ "department": contact.departmentName,
99
+ "title": contact.jobTitle
100
+ ]]
101
+ }
102
+
103
+ if wants("birthday", desired), contact.isKeyAvailable(CNContactBirthdayKey), var birthday = contact.birthday {
104
+ if birthday.year == nil { birthday.year = 1970 }
105
+ if let date = Calendar.current.date(from: birthday) {
106
+ dict["birthday"] = date.timeIntervalSince1970 * 1000.0
107
+ }
108
+ }
109
+
110
+ // `note` requires the restricted contacts-notes entitlement on iOS; only
111
+ // read it when it was actually fetched (i.e. the entitlement is present
112
+ // and the key was added to `fetchKeys`).
113
+ if wants("note", desired) && contact.isKeyAvailable(CNContactNoteKey) && !contact.note.isEmpty {
114
+ dict["note"] = contact.note
115
+ }
116
+
117
+ if wants("photos", desired) {
118
+ let thumbnail = contact.isKeyAvailable(CNContactThumbnailImageDataKey) ? contact.thumbnailImageData : nil
119
+ let full = contact.isKeyAvailable(CNContactImageDataKey) ? contact.imageData : nil
120
+ if let imageData = full ?? thumbnail, let path = photoTempFile(imageData, identifier: contact.identifier) {
121
+ dict["photos"] = [field(id: nil, value: path, type: "url")]
122
+ }
123
+ }
124
+
125
+ return dict
126
+ }
127
+
128
+ private func addressDictionary(_ labeled: CNLabeledValue<CNPostalAddress>) -> [String: Any] {
129
+ let postal = labeled.value
130
+ var address: [String: Any] = [:]
131
+ address["id"] = labeled.identifier
132
+ address["pref"] = false
133
+ address["type"] = canonicalLabel(labeled.label)
134
+ address["formatted"] = CNPostalAddressFormatter.string(from: postal, style: .mailingAddress)
135
+ address["streetAddress"] = postal.street
136
+ address["locality"] = postal.city
137
+ address["region"] = postal.state
138
+ address["postalCode"] = postal.postalCode
139
+ address["country"] = postal.country
140
+ return address
141
+ }
142
+
143
+ private func field(id: String?, value: String, type: String) -> [String: Any] {
144
+ var result: [String: Any] = [:]
145
+ if let id = id { result["id"] = id }
146
+ result["value"] = value
147
+ result["type"] = type
148
+ result["pref"] = false
149
+ return result
150
+ }
151
+
152
+ /// Maps system labels to fixed English strings ("home", "work", ...) so
153
+ /// both platforms return the same values regardless of device language.
154
+ /// Custom labels pass through unchanged.
155
+ private func canonicalLabel(_ label: String?) -> String {
156
+ switch label {
157
+ case nil, "": return "other"
158
+ case CNLabelHome: return "home"
159
+ case CNLabelWork: return "work"
160
+ case CNLabelOther: return "other"
161
+ case CNLabelPhoneNumberMobile: return "mobile"
162
+ case CNLabelPhoneNumberMain: return "main"
163
+ case CNLabelPhoneNumberiPhone: return "iphone"
164
+ case CNLabelPhoneNumberPager: return "pager"
165
+ case CNLabelURLAddressHomePage: return "homepage"
166
+ case CNLabelEmailiCloud: return "icloud"
167
+ case CNLabelDateAnniversary: return "anniversary"
168
+ default:
169
+ let label = label ?? ""
170
+ // System labels are "_$!<Name>!$_"-wrapped; localize unknown ones.
171
+ if label.hasPrefix("_$!<") {
172
+ return CNLabeledValue<NSString>.localizedString(forLabel: label).lowercased()
173
+ }
174
+ return label.lowercased()
175
+ }
176
+ }
177
+
178
+ // MARK: - Mapping dictionary -> CNMutableContact
179
+
180
+ func apply(_ dict: [String: Any], to contact: CNMutableContact) {
181
+ // A field present in the payload replaces the stored value entirely;
182
+ // absent fields are left untouched (matches the Android side).
183
+ if let name = dict["name"] as? [String: Any] {
184
+ contact.givenName = name["givenName"] as? String ?? ""
185
+ contact.familyName = name["familyName"] as? String ?? ""
186
+ contact.middleName = name["middleName"] as? String ?? ""
187
+ contact.namePrefix = name["honorificPrefix"] as? String ?? ""
188
+ contact.nameSuffix = name["honorificSuffix"] as? String ?? ""
189
+ }
190
+
191
+ if let nickname = dict["nickname"] as? String {
192
+ contact.nickname = nickname
193
+ }
194
+
195
+ // `note` is intentionally not written on iOS: setting it requires the
196
+ // restricted `com.apple.developer.contacts.notes` entitlement, and
197
+ // saving with a note set throws without it. Documented as iOS-unsupported.
198
+
199
+ if let phoneNumbers = dict["phoneNumbers"] as? [[String: Any]] {
200
+ contact.phoneNumbers = phoneNumbers.compactMap { entry in
201
+ guard let value = entry["value"] as? String, !value.isEmpty else { return nil }
202
+ return CNLabeledValue(
203
+ label: labelKey(entry["type"] as? String),
204
+ value: CNPhoneNumber(stringValue: value)
205
+ )
206
+ }
207
+ }
208
+
209
+ if let emails = dict["emails"] as? [[String: Any]] {
210
+ contact.emailAddresses = emails.compactMap { entry in
211
+ guard let value = entry["value"] as? String, !value.isEmpty else { return nil }
212
+ return CNLabeledValue(label: labelKey(entry["type"] as? String), value: value as NSString)
213
+ }
214
+ }
215
+
216
+ if let urls = dict["urls"] as? [[String: Any]] {
217
+ contact.urlAddresses = urls.compactMap { entry in
218
+ guard let value = entry["value"] as? String, !value.isEmpty else { return nil }
219
+ return CNLabeledValue(label: labelKey(entry["type"] as? String), value: value as NSString)
220
+ }
221
+ }
222
+
223
+ if let addresses = dict["addresses"] as? [[String: Any]] {
224
+ contact.postalAddresses = addresses.compactMap { address in
225
+ let postal = CNMutablePostalAddress()
226
+ postal.street = (address["streetAddress"] as? String) ?? ""
227
+ postal.city = (address["locality"] as? String) ?? ""
228
+ postal.state = (address["region"] as? String) ?? ""
229
+ postal.postalCode = (address["postalCode"] as? String) ?? ""
230
+ postal.country = (address["country"] as? String) ?? ""
231
+ return CNLabeledValue(label: labelKey(address["type"] as? String), value: postal)
232
+ }
233
+ }
234
+
235
+ if let ims = dict["ims"] as? [[String: Any]] {
236
+ contact.instantMessageAddresses = ims.compactMap { entry in
237
+ guard let value = entry["value"] as? String, !value.isEmpty else { return nil }
238
+ let service = (entry["type"] as? String) ?? ""
239
+ return CNLabeledValue(
240
+ label: nil,
241
+ value: CNInstantMessageAddress(username: value, service: service)
242
+ )
243
+ }
244
+ }
245
+
246
+ if let organizations = dict["organizations"] as? [[String: Any]], let org = organizations.first {
247
+ contact.organizationName = (org["name"] as? String) ?? ""
248
+ contact.departmentName = (org["department"] as? String) ?? ""
249
+ contact.jobTitle = (org["title"] as? String) ?? ""
250
+ }
251
+
252
+ if let birthdayMs = (dict["birthday"] as? NSNumber)?.doubleValue {
253
+ let date = Date(timeIntervalSince1970: birthdayMs / 1000.0)
254
+ contact.birthday = Calendar.current.dateComponents([.year, .month, .day], from: date)
255
+ }
256
+
257
+ if let photos = dict["photos"] as? [[String: Any]], let photo = photos.first,
258
+ let data = photoData(from: photo) {
259
+ contact.imageData = data
260
+ }
261
+ }
262
+
263
+ /// Writes the photo to a file in the app's temporary directory and
264
+ /// returns its path; photo reads carry this path in the `url` field.
265
+ /// The system clears the temporary directory, so the path is short-lived.
266
+ private func photoTempFile(_ data: Data, identifier: String) -> String? {
267
+ let name = "contact_photo_" + identifier.replacingOccurrences(of: ":", with: "-")
268
+ let path = (NSTemporaryDirectory() as NSString).appendingPathComponent(name)
269
+ do {
270
+ try data.write(to: URL(fileURLWithPath: path), options: .atomic)
271
+ return path
272
+ } catch {
273
+ return nil
274
+ }
275
+ }
276
+
277
+ /// Decodes the first photo entry into image bytes: `base64` values are
278
+ /// decoded directly; `url` values are read from local `file://` URLs or
279
+ /// bare file paths.
280
+ private func photoData(from photo: [String: Any]) -> Data? {
281
+ guard let value = photo["value"] as? String, !value.isEmpty else { return nil }
282
+ let type = (photo["type"] as? String)?.lowercased() ?? "url"
283
+ if type == "base64" {
284
+ return Data(base64Encoded: value, options: .ignoreUnknownCharacters)
285
+ }
286
+ if let url = URL(string: value), url.isFileURL {
287
+ return try? Data(contentsOf: url)
288
+ }
289
+ // Photo reads return bare paths, so accept those as well.
290
+ if value.hasPrefix("/") {
291
+ return try? Data(contentsOf: URL(fileURLWithPath: value))
292
+ }
293
+ return nil
294
+ }
295
+
296
+ /// Maps a free-form label string to a Contacts framework label constant.
297
+ private func labelKey(_ type: String?) -> String {
298
+ switch type?.lowercased() {
299
+ case "home": return CNLabelHome
300
+ case "work": return CNLabelWork
301
+ case "mobile", "cell": return CNLabelPhoneNumberMobile
302
+ case "main": return CNLabelPhoneNumberMain
303
+ case "iphone": return CNLabelPhoneNumberiPhone
304
+ case "pager": return CNLabelPhoneNumberPager
305
+ case "homepage": return CNLabelURLAddressHomePage
306
+ case "other", nil, "": return CNLabelOther
307
+ default: return type ?? CNLabelOther
308
+ }
309
+ }
310
+ }