@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,166 @@
1
+ import Capacitor
2
+ import Contacts
3
+ import ContactsUI
4
+ import Foundation
5
+
6
+ /// Capacitor bridge for the Contacts plugin.
7
+ ///
8
+ /// Permission model is **implicit**: there are no `checkPermissions` /
9
+ /// `requestPermissions` methods. `find`, `save` and `remove` request Contacts
10
+ /// access before touching the store. On iOS 18+ Limited Access counts as
11
+ /// granted. `pickContact` presents the system picker, which requires no
12
+ /// permission at all.
13
+ @objc(ContactsPlugin)
14
+ public class ContactsPlugin: CAPPlugin, CAPBridgedPlugin {
15
+ public let identifier = "ContactsPlugin"
16
+ public let jsName = "Contacts"
17
+ public let pluginMethods: [CAPPluginMethod] = [
18
+ CAPPluginMethod(name: "find", returnType: CAPPluginReturnPromise),
19
+ CAPPluginMethod(name: "save", returnType: CAPPluginReturnPromise),
20
+ CAPPluginMethod(name: "remove", returnType: CAPPluginReturnPromise),
21
+ CAPPluginMethod(name: "pickContact", returnType: CAPPluginReturnPromise)
22
+ ]
23
+
24
+ private let implementation = Contacts()
25
+
26
+ /// Call awaiting the result of the contact picker UI.
27
+ private var pickCall: CAPPluginCall?
28
+
29
+ // MARK: - find
30
+
31
+ @objc func find(_ call: CAPPluginCall) {
32
+ guard let fields = call.getArray("fields") as? [String], !fields.isEmpty else {
33
+ reject(call, .invalidArgument)
34
+ return
35
+ }
36
+ let filter = call.getString("filter") ?? ""
37
+ let multiple = call.getBool("multiple") ?? false
38
+ let desired = (call.getArray("desiredFields") as? [String]) ?? []
39
+ let hasPhoneNumber = call.getBool("hasPhoneNumber") ?? false
40
+
41
+ withAccess(call) {
42
+ do {
43
+ let contacts = try self.implementation.search(
44
+ fields: fields,
45
+ filter: filter,
46
+ multiple: multiple,
47
+ desiredFields: desired,
48
+ hasPhoneNumber: hasPhoneNumber
49
+ )
50
+ call.resolve(["contacts": contacts])
51
+ } catch {
52
+ self.reject(call, error as? ContactsError ?? .unknown)
53
+ }
54
+ }
55
+ }
56
+
57
+ // MARK: - save
58
+
59
+ @objc func save(_ call: CAPPluginCall) {
60
+ guard let contact = call.getObject("contact") else {
61
+ reject(call, .invalidArgument)
62
+ return
63
+ }
64
+ withAccess(call) {
65
+ do {
66
+ let saved = try self.implementation.save(contact: contact)
67
+ call.resolve(saved)
68
+ } catch {
69
+ self.reject(call, error as? ContactsError ?? .unknown)
70
+ }
71
+ }
72
+ }
73
+
74
+ // MARK: - remove
75
+
76
+ @objc func remove(_ call: CAPPluginCall) {
77
+ guard let id = call.getString("id"), !id.isEmpty else {
78
+ reject(call, .invalidArgument)
79
+ return
80
+ }
81
+ withAccess(call) {
82
+ do {
83
+ try self.implementation.remove(id: id)
84
+ call.resolve()
85
+ } catch {
86
+ self.reject(call, error as? ContactsError ?? .unknown)
87
+ }
88
+ }
89
+ }
90
+
91
+ // MARK: - pickContact
92
+
93
+ /// Presents `CNContactPickerViewController`, which runs out of process and
94
+ /// needs no Contacts permission, the recommended flow under iOS 18+
95
+ /// Limited Access (the full contact list is shown and only the picked
96
+ /// contact's data is returned to the app).
97
+ @objc func pickContact(_ call: CAPPluginCall) {
98
+ DispatchQueue.main.async {
99
+ guard self.pickCall == nil else {
100
+ self.reject(call, .pendingOperation)
101
+ return
102
+ }
103
+ guard let viewController = self.bridge?.viewController else {
104
+ self.reject(call, .unknown)
105
+ return
106
+ }
107
+ self.pickCall = call
108
+ let picker = CNContactPickerViewController()
109
+ picker.delegate = self
110
+ // Present from the top-most controller so an already-presented
111
+ // modal doesn't make present() fail silently (stuck pick state).
112
+ var presenter = viewController
113
+ while let presented = presenter.presentedViewController {
114
+ presenter = presented
115
+ }
116
+ presenter.present(picker, animated: true)
117
+ }
118
+ }
119
+
120
+ // MARK: - Implicit permission handling
121
+
122
+ /// Ensures Contacts access (full, or limited on iOS 18+), then runs
123
+ /// `work` off the main thread. Rejects with `OS-PLUG-CONT-0020` when
124
+ /// access is refused.
125
+ private func withAccess(_ call: CAPPluginCall, work: @escaping () -> Void) {
126
+ if implementation.isAuthorized() {
127
+ DispatchQueue.global(qos: .userInitiated).async { work() }
128
+ return
129
+ }
130
+ implementation.requestAccess { granted in
131
+ if granted {
132
+ DispatchQueue.global(qos: .userInitiated).async { work() }
133
+ } else {
134
+ self.reject(call, .permissionDenied)
135
+ }
136
+ }
137
+ }
138
+
139
+ private func reject(_ call: CAPPluginCall, _ error: ContactsError) {
140
+ call.reject(error.message, error.code)
141
+ }
142
+ }
143
+
144
+ // MARK: - CNContactPickerDelegate
145
+
146
+ extension ContactsPlugin: CNContactPickerDelegate {
147
+ public func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
148
+ let call = pickCall
149
+ pickCall = nil
150
+ guard let call = call else { return }
151
+ // When the store is readable, re-fetch by identifier for the full key
152
+ // set. Without access (picker needs none), map the picker's contact
153
+ // directly; the mapper guards every key with `isKeyAvailable`.
154
+ if implementation.isAuthorized(), let full = implementation.getContact(byId: contact.identifier) {
155
+ call.resolve(full)
156
+ } else {
157
+ call.resolve(implementation.contactToDictionary(contact, desiredFields: []))
158
+ }
159
+ }
160
+
161
+ public func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
162
+ let call = pickCall
163
+ pickCall = nil
164
+ call?.reject(ContactsError.operationCancelled.message, ContactsError.operationCancelled.code)
165
+ }
166
+ }
@@ -0,0 +1,69 @@
1
+ import Contacts
2
+ import XCTest
3
+
4
+ @testable import ContactsPlugin
5
+
6
+ class ContactsTests: XCTestCase {
7
+
8
+ func testErrorCodesFollowUnifiedFormat() {
9
+ XCTAssertEqual(ContactsError.unknown.code, "OS-PLUG-CONT-0000")
10
+ XCTAssertEqual(ContactsError.invalidArgument.code, "OS-PLUG-CONT-0001")
11
+ XCTAssertEqual(ContactsError.timeout.code, "OS-PLUG-CONT-0002")
12
+ XCTAssertEqual(ContactsError.pendingOperation.code, "OS-PLUG-CONT-0003")
13
+ XCTAssertEqual(ContactsError.ioError.code, "OS-PLUG-CONT-0004")
14
+ XCTAssertEqual(ContactsError.notSupported.code, "OS-PLUG-CONT-0005")
15
+ XCTAssertEqual(ContactsError.operationCancelled.code, "OS-PLUG-CONT-0006")
16
+ XCTAssertEqual(ContactsError.permissionDenied.code, "OS-PLUG-CONT-0020")
17
+ }
18
+
19
+ func testContactToDictionaryMapsWireFormat() {
20
+ let contact = CNMutableContact()
21
+ contact.givenName = "Ada"
22
+ contact.familyName = "Lovelace"
23
+ contact.nickname = "Countess"
24
+ contact.organizationName = "Analytical Engines"
25
+ contact.jobTitle = "Mathematician"
26
+ contact.phoneNumbers = [
27
+ CNLabeledValue(label: CNLabelPhoneNumberMobile, value: CNPhoneNumber(stringValue: "+351910000000"))
28
+ ]
29
+ contact.emailAddresses = [
30
+ CNLabeledValue(label: CNLabelHome, value: "ada@example.com" as NSString)
31
+ ]
32
+ contact.birthday = DateComponents(year: 1815, month: 12, day: 10)
33
+
34
+ let dict = Contacts().contactToDictionary(contact, desiredFields: [])
35
+
36
+ XCTAssertNotNil(dict["id"] as? String)
37
+ let name = dict["name"] as? [String: Any]
38
+ XCTAssertEqual(name?["givenName"] as? String, "Ada")
39
+ XCTAssertEqual(name?["familyName"] as? String, "Lovelace")
40
+ XCTAssertEqual(dict["nickname"] as? String, "Countess")
41
+
42
+ let phones = dict["phoneNumbers"] as? [[String: Any]]
43
+ XCTAssertEqual(phones?.count, 1)
44
+ XCTAssertEqual(phones?.first?["value"] as? String, "+351910000000")
45
+
46
+ let emails = dict["emails"] as? [[String: Any]]
47
+ XCTAssertEqual(emails?.first?["value"] as? String, "ada@example.com")
48
+
49
+ let organizations = dict["organizations"] as? [[String: Any]]
50
+ XCTAssertEqual(organizations?.first?["name"] as? String, "Analytical Engines")
51
+
52
+ XCTAssertNotNil(dict["birthday"] as? Double)
53
+ }
54
+
55
+ func testContactToDictionaryHonorsDesiredFields() {
56
+ let contact = CNMutableContact()
57
+ contact.givenName = "Grace"
58
+ contact.phoneNumbers = [
59
+ CNLabeledValue(label: CNLabelPhoneNumberMobile, value: CNPhoneNumber(stringValue: "+14085550100"))
60
+ ]
61
+
62
+ let dict = Contacts().contactToDictionary(contact, desiredFields: ["phoneNumbers"])
63
+
64
+ XCTAssertNotNil(dict["id"] as? String)
65
+ XCTAssertNotNil(dict["phoneNumbers"])
66
+ XCTAssertNil(dict["name"])
67
+ XCTAssertNil(dict["displayName"])
68
+ }
69
+ }
package/package.json ADDED
@@ -0,0 +1,92 @@
1
+ {
2
+ "name": "@capacitor/contacts",
3
+ "version": "0.0.1",
4
+ "description": "Access, search, pick, create, update and remove device contacts.",
5
+ "main": "dist/plugin.cjs.js",
6
+ "module": "dist/esm/index.js",
7
+ "types": "dist/esm/index.d.ts",
8
+ "unpkg": "dist/plugin.js",
9
+ "files": [
10
+ "CapacitorContacts.podspec",
11
+ "LICENSE",
12
+ "NOTICE",
13
+ "Package.swift",
14
+ "android/build.gradle",
15
+ "android/src/main/",
16
+ "dist/",
17
+ "ios/Sources",
18
+ "ios/Tests"
19
+ ],
20
+ "author": "OutSystems <support@outsystems.com>",
21
+ "license": "Apache-2.0",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/ionic-team/capacitor-contacts.git"
25
+ },
26
+ "bugs": {
27
+ "url": "https://github.com/ionic-team/capacitor-contacts/issues"
28
+ },
29
+ "keywords": [
30
+ "capacitor",
31
+ "plugin",
32
+ "native"
33
+ ],
34
+ "scripts": {
35
+ "verify": "npm run verify:ios && npm run verify:android && npm run verify:web",
36
+ "verify:ios": "xcodebuild -scheme CapacitorContacts -destination generic/platform=iOS",
37
+ "verify:android": "cd android && ./gradlew clean build test && cd ..",
38
+ "verify:web": "npm run build",
39
+ "lint": "npm run eslint && npm run prettier -- --check && npm run swiftlint -- lint",
40
+ "fmt": "npm run eslint -- --fix && npm run prettier -- --write && npm run swiftlint -- --fix --format",
41
+ "eslint": "eslint . --ext ts",
42
+ "prettier": "prettier \"**/*.{css,html,ts,js,java}\" --plugin=prettier-plugin-java",
43
+ "swiftlint": "node-swiftlint",
44
+ "docgen": "docgen --api ContactsPlugin --output-readme README.md --output-json dist/docs.json",
45
+ "build": "npm run clean && npm run docgen && tsc && rollup -c rollup.config.mjs",
46
+ "clean": "rimraf ./dist",
47
+ "watch": "tsc --watch",
48
+ "prepare": "npm run build",
49
+ "prepublishOnly": "npm run build",
50
+ "publish:cocoapod": "pod trunk push ./CapacitorContacts.podspec --allow-warnings"
51
+ },
52
+ "devDependencies": {
53
+ "@capacitor/android": "^8.0.0",
54
+ "@capacitor/core": "^8.0.0",
55
+ "@capacitor/docgen": "^0.3.1",
56
+ "@capacitor/ios": "^8.0.0",
57
+ "@ionic/eslint-config": "^0.4.0",
58
+ "@ionic/prettier-config": "^4.0.0",
59
+ "@ionic/swiftlint-config": "^2.0.0",
60
+ "eslint": "^8.57.1",
61
+ "prettier": "^3.6.2",
62
+ "prettier-plugin-java": "^2.7.7",
63
+ "rimraf": "^6.1.0",
64
+ "rollup": "^4.53.2",
65
+ "swiftlint": "^2.0.0",
66
+ "typescript": "^5.9.3",
67
+ "@semantic-release/changelog": "^6.0.3",
68
+ "@semantic-release/git": "^10.0.1",
69
+ "@semantic-release/github": "^12.0.2",
70
+ "@semantic-release/npm": "^13.1.2",
71
+ "semantic-release": "^25.0.2"
72
+ },
73
+ "peerDependencies": {
74
+ "@capacitor/core": ">=8.0.0"
75
+ },
76
+ "prettier": "@ionic/prettier-config",
77
+ "swiftlint": "@ionic/swiftlint-config",
78
+ "eslintConfig": {
79
+ "extends": "@ionic/eslint-config/recommended"
80
+ },
81
+ "capacitor": {
82
+ "ios": {
83
+ "src": "ios"
84
+ },
85
+ "android": {
86
+ "src": "android"
87
+ }
88
+ },
89
+ "publishConfig": {
90
+ "access": "public"
91
+ }
92
+ }