开始使用联系人
本指南将引导您将 Capacitor 联系人插件集成到您的应用程序中。
使用 npm 安装插件:
npm install @capgo/capacitor-contactsnpx cap synciOS 配置
Section titled “iOS 配置”将以下内容添加到您的 Info.plist 中:
<key>NSContactsUsageDescription</key><string>This app needs access to contacts to let you select recipients</string>Android 配置
Section titled “Android 配置”将以下权限添加到您的 AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_CONTACTS" /><uses-permission android:name="android.permission.WRITE_CONTACTS" />import { Contacts } from '@capgo/capacitor-contacts';const requestPermissions = async () => { const permission = await Contacts.requestPermissions(); console.log('Permission status:', permission.contacts);};获取所有联系人
Section titled “获取所有联系人”const getAllContacts = async () => { const result = await Contacts.getContacts({ projection: { name: true, phones: true, emails: true, image: true } });
console.log('Contacts:', result.contacts);};const searchContacts = async (query: string) => { const result = await Contacts.getContacts({ projection: { name: true, phones: true, emails: true }, query: query });
console.log('Search results:', result.contacts);};const createContact = async () => { const newContact = { name: { given: 'John', family: 'Doe' }, phones: [{ type: 'mobile', number: '+1234567890' }], emails: [{ type: 'work', address: 'john.doe@example.com' }] };
const result = await Contacts.createContact(newContact); console.log('Contact created:', result);};更新联系方式
Section titled “更新联系方式”const updateContact = async (contactId: string) => { const updates = { contactId: contactId, name: { given: 'Jane', family: 'Doe' } };
await Contacts.updateContact(updates); console.log('Contact updated');};const deleteContact = async (contactId: string) => { await Contacts.deleteContact({ contactId }); console.log('Contact deleted');};以下是联系服务的完整示例:
import { Contacts } from '@capgo/capacitor-contacts';
interface Contact { contactId: string; name: { display?: string; given?: string; family?: string; }; phones?: Array<{ type: string; number: string }>; emails?: Array<{ type: string; address: string }>; image?: { base64String: string };}
class ContactsService { async checkPermissions(): Promise<boolean> { const permission = await Contacts.checkPermissions();
if (permission.contacts === 'granted') { return true; }
const requested = await Contacts.requestPermissions(); return requested.contacts === 'granted'; }
async getAllContacts(): Promise<Contact[]> { const hasPermission = await this.checkPermissions(); if (!hasPermission) { throw new Error('Contacts permission denied'); }
const result = await Contacts.getContacts({ projection: { name: true, phones: true, emails: true, image: true } });
return result.contacts; }
async searchContacts(query: string): Promise<Contact[]> { if (!query || query.length < 2) { return []; }
const result = await Contacts.getContacts({ projection: { name: true, phones: true, emails: true }, query: query });
return result.contacts; }
async getContactById(contactId: string): Promise<Contact | null> { const result = await Contacts.getContacts({ projection: { name: true, phones: true, emails: true, image: true, organization: true, birthday: true, note: true, urls: true, postalAddresses: true }, contactId: contactId });
return result.contacts.length > 0 ? result.contacts[0] : null; }
async createContact(contact: Partial<Contact>): Promise<string> { const hasPermission = await this.checkPermissions(); if (!hasPermission) { throw new Error('Contacts permission denied'); }
const result = await Contacts.createContact(contact); return result.contactId; }
async updateContact(contactId: string, updates: Partial<Contact>): Promise<void> { await Contacts.updateContact({ contactId, ...updates }); }
async deleteContact(contactId: string): Promise<void> { await Contacts.deleteContact({ contactId }); }
formatPhoneNumber(phone: string): string { // Remove non-numeric characters const cleaned = phone.replace(/\D/g, '');
// Format as (XXX) XXX-XXXX if (cleaned.length === 10) { return `(${cleaned.slice(0, 3)}) ${cleaned.slice(3, 6)}-${cleaned.slice(6)}`; }
return phone; }
getContactInitials(contact: Contact): string { const given = contact.name?.given || ''; const family = contact.name?.family || '';
if (given && family) { return `${given[0]}${family[0]}`.toUpperCase(); }
const display = contact.name?.display || ''; const parts = display.split(' ');
if (parts.length >= 2) { return `${parts[0][0]}${parts[1][0]}`.toUpperCase(); }
return display.slice(0, 2).toUpperCase(); }}
// Usageconst contactsService = new ContactsService();
// Get all contactsconst contacts = await contactsService.getAllContacts();console.log('Contacts:', contacts);
// Search contactsconst results = await contactsService.searchContacts('john');console.log('Search results:', results);
// Create contactconst newContactId = await contactsService.createContact({ name: { given: 'Jane', family: 'Smith' }, phones: [{ type: 'mobile', number: '+1234567890' }]});
// Update contactawait contactsService.updateContact(newContactId, { emails: [{ type: 'work', address: 'jane@example.com' }]});projection 参数控制要获取的字段:
const result = await Contacts.getContacts({ projection: { name: true, // Contact name phones: true, // Phone numbers emails: true, // Email addresses image: true, // Contact photo organization: true, // Company/organization birthday: true, // Birth date note: true, // Notes urls: true, // Websites postalAddresses: true // Physical addresses }});提示:仅请求提高性能所需的字段。
联系选择器 UI
Section titled “联系选择器 UI”许多应用程序更喜欢使用本机联系人选择器:
const pickContact = async () => { try { const result = await Contacts.pickContact({ projection: { name: true, phones: true, emails: true } });
if (result.contacts.length > 0) { const contact = result.contacts[0]; console.log('Selected contact:', contact); } } catch (error) { console.error('Contact picker cancelled or failed:', error); }};- 请求最小权限:仅在需要时请求联系人权限
- 使用投影:只获取你实际使用的字段
- 处理拒绝:当权限被拒绝时提供后备
- 明智地缓存:联系人可能会更改,不要缓存太久
- 尊重隐私:联系人使用情况保持透明
- 异步操作:所有联系操作都是异步的
const handlePermissionDenied = async () => { const permission = await Contacts.checkPermissions();
if (permission.contacts === 'denied') { // Show dialog explaining why permission is needed showPermissionDialog(); // Direct user to settings // On iOS: Settings > [App] > Contacts // On Android: Settings > Apps > [App] > Permissions }};大型联系人列表
Section titled “大型联系人列表”const loadContactsInBatches = async () => { // Get count first (lightweight) const projection = { name: true }; // Minimal projection
// Implement pagination if needed const allContacts = await Contacts.getContacts({ projection });
// Process in chunks const chunkSize = 100; for (let i = 0; i < allContacts.contacts.length; i += chunkSize) { const chunk = allContacts.contacts.slice(i, i + chunkSize); await processContactChunk(chunk); }};