RN Lez 30: Share, Linking, Vibration
Docs: Share, Linking, Vibration
Obiettivi
Section titled “Obiettivi”- Condividere contenuti con Share API
- Aprire link esterni con Linking
- Usare Vibration per feedback tattile
1. Share — condividere
Section titled “1. Share — condividere”import { Share } from 'react-native';
const condividi = async (messaggio: string) => { try { await Share.share({ message: messaggio, // testo da condividere title: 'Guarda questo!', // solo Android }); } catch (err) { console.error(err); }};Esempio: condividere citazione
Section titled “Esempio: condividere citazione”<TouchableOpacity onPress={() => condividi(`"${citazione}" — ${autore}`)}> <Text>📤 Condividi</Text></TouchableOpacity>2. Linking — aprire URL
Section titled “2. Linking — aprire URL”import { Linking } from 'react-native';
// Aprire sito webconst apriURL = async (url: string) => { const supportato = await Linking.canOpenURL(url); if (supportato) { await Linking.openURL(url); } else { Alert.alert('Errore', `Impossibile aprire: ${url}`); }};
// Aprire emailconst apriEmail = (email: string) => { Linking.openURL(`mailto:${email}`);};
// Aprire telefonoconst chiama = (numero: string) => { Linking.openURL(`tel:${numero}`);};
// Aprire mappe (Android)const apriMappe = (lat: number, lng: number) => { const url = Platform.select({ ios: `maps://?q=${lat},${lng}`, android: `geo:${lat},${lng}?q=${lat},${lng}`, }); Linking.openURL(url!);};3. Vibration — vibrazione
Section titled “3. Vibration — vibrazione”import { Vibration } from 'react-native';
// Vibrazione singola (400ms)Vibration.vibrate(400);
// Pattern: vibra 200ms, ferma 100ms, vibra 200msVibration.vibrate([200, 100, 200], false);// ↑ false = non ripetere
// Fermare vibrazioneVibration.cancel();4. BackHandler — gestire tasto indietro (Android)
Section titled “4. BackHandler — gestire tasto indietro (Android)”import { BackHandler } from 'react-native';import { useEffect } from 'react';
useEffect(() => { const backHandler = BackHandler.addEventListener('hardwareBackPress', () => { Alert.alert('Uscire?', 'Vuoi chiudere l\'app?', [ { text: 'No', style: 'cancel' }, { text: 'Sì', onPress: () => BackHandler.exitApp() }, ]); return true; // ← blocca comportamento default }); return () => backHandler.remove(); // cleanup}, []);5. Tabella riassuntiva
Section titled “5. Tabella riassuntiva”| API | Codice |
|---|---|
| Share | Share.share({ message: '...' }) |
| Linking URL | Linking.openURL(url) |
| Linking canOpen | Linking.canOpenURL(url) |
| Vibration | Vibration.vibrate(ms) |
| BackHandler | BackHandler.addEventListener(...) |
6. Esercizio
Section titled “6. Esercizio”🎯 “App informativa”
Section titled “🎯 “App informativa””Crea un’app che:
- Mostra un contatto (nome, email, telefono)
- Bottone “Chiama” → apre telefono
- Bottone “Email” → apre mail
- Bottone “Sito web” → apre browser
- Bottone “Condividi” → condivide contatto
- Bottone vibrazione lunga (500ms)
- Gestione BackHandler su Android con conferma