Iniziare con i contatti
Questa guida ti guiderà attraverso l’integrazione del plug-in Capacitor Contatti nella tua applicazione.
Installazione
Section titled “Installazione”Installa il plug-in utilizzando npm:
npm install @capgo/capacitor-contactsnpx cap synciOS Configurazione
Section titled “iOS Configurazione”Aggiungi quanto segue al tuo Info.plist:
<key>NSContactsUsageDescription</key><string>This app needs access to contacts to let you select recipients</string>Android Configurazione
Section titled “Android Configurazione”Aggiungi le seguenti autorizzazioni al tuo AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_CONTACTS" /><uses-permission android:name="android.permission.WRITE_CONTACTS" />Utilizzo di base
Section titled “Utilizzo di base”Importa il plugin
Section titled “Importa il plugin”import { Contacts } from '@capgo/capacitor-contacts';Richiedi autorizzazioni
Section titled “Richiedi autorizzazioni”const requestPermissions = async () => { const permission = await Contacts.requestPermissions(); console.log('Permission status:', permission.contacts);};Ottieni tutti i contatti
Section titled “Ottieni tutti i contatti”const getAllContacts = async () => { const result = await Contacts.getContacts({ projection: { name: true, phones: true, emails: true, image: true } });
console.log('Contacts:', result.contacts);};Cerca contatti
Section titled “Cerca contatti”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);};Crea contatto
Section titled “Crea contatto”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);};Aggiorna contatto
Section titled “Aggiorna contatto”const updateContact = async (contactId: string) => { const updates = { contactId: contactId, name: { given: 'Jane', family: 'Doe' } };
await Contacts.updateContact(updates); console.log('Contact updated');};Elimina contatto
Section titled “Elimina contatto”const deleteContact = async (contactId: string) => { await Contacts.deleteContact({ contactId }); console.log('Contact deleted');};Esempio completo
Section titled “Esempio completo”Ecco un esempio completo con un servizio di contatto:
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' }]});Comprendere la proiezione
Section titled “Comprendere la proiezione”Il parametro projection controlla quali campi recuperare:
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 }});Suggerimento: richiedi solo i campi necessari per migliorare le prestazioni.
Interfaccia utente del selettore di contatti
Section titled “Interfaccia utente del selettore di contatti”Molte app preferiscono utilizzare il selettore di contatti nativo:
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); }};Migliori pratiche
Section titled “Migliori pratiche”- Richiedi autorizzazioni minime: richiedi l’autorizzazione ai contatti solo quando necessario
- Utilizza proiezione: recupera solo i campi effettivamente utilizzati
- Gestisci rifiuti: fornisce fallback quando le autorizzazioni vengono negate
- Memorizza nella cache con saggezza: i contatti possono cambiare, non memorizzare nella cache troppo a lungo
- Rispetta la privacy: sii trasparente sull’utilizzo dei contatti
- Operazioni asincrone: tutte le operazioni sui contatti sono asincrone
Problemi comuni
Section titled “Problemi comuni”Autorizzazione negata
Section titled “Autorizzazione negata”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 }};Elenchi di contatti di grandi dimensioni
Section titled “Elenchi di contatti di grandi dimensioni”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); }};Passaggi successivi
Section titled “Passaggi successivi”- Esplora il API Riferimento per la documentazione completa del metodo
- Controlla l’app di esempio per un utilizzo avanzato
- Consulta il tutorial per esempi di implementazione completi