Token alma
- React Native kursu
- İleri seviye
- Ders 2/83
- 5 dk
Push token alma öğrenirsin.
Push token nedir?
Bir push token, cihazını benzersiz biçimde tanıtan bir dizedir. Sunucun bu dizeye bildirim gönderir; Apple veya Google'ın hizmeti token'ı gerçek cihaza yönlendirir. Token olmadan uzak bildirim gönderemezsin.
expo-notifications paketi getExpoPushTokenAsync işleviyle bir Expo token'ı döndürür. Bu token ExponentPushToken[xxxxxxxxxxxxxxx] biçimindedir. Token'ı şunucuna kaydedersin; sunucun bildirim göndermek istediğinde bu token'ı kullanır.
Android kanalı
Android 8 ve sonrasında bildirimler bir kanala bağlanmalıdır. Kanal, bildirimin sesini, önem derecesini ve davranışını belirler. iOS'ta kanal kavramı yoktur; bu yüzden kanal ayarları yalnızca Android için geçerlidir.
Bir kanal oluşturmak için Notifications.setNotificationChannelAsync çağrılır. Örnek: Notifications.setNotificationChannelAsync('default', {{ name: 'Varsayılan', importance: Notifications.AndroidImportance.HIGH }}). Bu çağrı uygulama başlarken bir kez yapılır; sonra aynı kanal adını bildirimlere verirsin.
Uygulama Token al ve konsola yaz
registerForPushNotifications işlevini tamamla. Önce Notifications.getPermissionsAsync() ile izin durumunu al; granted değilse Notifications.requestPermissionsAsync() çağır. Sonra const token = await Notifications.getExpoPushTokenAsync({{ projectId: 'abc123' }}) ile token'ı al ve console.log(token.data) yaz.
Başlangıç kodu
import * as Notifications from 'expo-notifications';
export async function registerForPushNotifications() {
// izinleri kontrol et, gerekirse iste
// token al ve konsola yaz
}Örnek çözüm
async function registerForPushNotifications() {
const current = await Notifications.getPermissionsAsync();
let final = current;
if (!final.granted) {
final = await Notifications.requestPermissionsAsync();
}
if (!final.granted) return null;
const token = await Notifications.getExpoPushTokenAsync({ projectId: 'abc123' });
console.log(token.data);
return token.data;
}Soru ve cevaplar
Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.
1 Token alma işlevini yaz
const token = await Notifications.____({ projectId: 'your-project-id' });
const token = await Notifications.getExpoPushTokenAsync({ projectId: 'your-project-id' });
Açıklama: getExpoPushTokenAsync bir Expo token'ı döndürür.
2 Push token ne için kullanılır?
- Yalnızca yerel bildirim zamanlamak için
- Sunucu bildirimi cihaza göndermek için Doğru cevap
- Kullanıcı parolasını saklamak için
- Uygulama simgesini değiştirmek için
Açıklama: Sunucu, token'a bildirim gönderir; hizmet cihaza iletir.
3 Parçayı rolüne eşle
| Kavram | Anlamı |
|---|---|
getExpoPushTokenAsync |
Expo token döndürür |
getPermissionsAsync |
İzin durumunu verir |
requestPermissionsAsync |
İzin ister |
token.data |
Token dizesini taşır |