Я использую REACT Native с толкающими лучами для уведомлений о толчке в моем приложении. < /p>
Проблема: < /p>
На моем эмуляторе iOS (iPhone 16 Pro Max, iOS 17+), фоновые уведомления о том, что я работаю правильно после того, как я включен фоновые моды>, а также на iPhone. Приложение не получает push -уведомления, когда оно находится в фоновом режиме или завершено.
Уведомления работают только тогда, когда приложение находится на переднем плане. /> Загружено правильный ключ APNS Auth Auth (.p8) на толкающие лучи с: идентификационным идентификатором идентификатором ключа идентификатор пакета < /p>
Переустановил приложение на эмуляторе и физическом устройстве. Есть ли какие -либо ограничения с более старыми версиями iOS или проблемами совместимости с APNS со старыми устройствами? Я упускаю что -то еще в настройке толкателя или Xcode?
Notifications.setNotificationHandler({
handleNotification: async (notification) => {
const notificationsEnabled = await getProgress('notificationsEnabled');
// Only show notifications if the user has enabled them
if (notificationsEnabled === 'true') {
return {
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: true,
};
} else {
return {
shouldShowAlert: false,
shouldPlaySound: false,
shouldSetBadge: false,
};
}
},
});
const App = () => {
const [notifications, setNotifications] = useState([]);
const [userRegionId, setUserRegionId] = useState(null);
const [notificationsEnabled, setNotificationsEnabled] = useState(false);
const requestPermissions = async () => {
try {
const { status } = await Notifications.getPermissionsAsync();
const isEnabled = status === 'granted';
setNotificationsEnabled(isEnabled);
await saveProgress('notificationsEnabled', isEnabled ? 'true' : 'false');
if (status === 'undetermined') {
const { status: newStatus } = await Notifications.requestPermissionsAsync();
const newIsEnabled = newStatus === 'granted';
setNotificationsEnabled(newIsEnabled);
await saveProgress('notificationsEnabled', newIsEnabled ? 'true' : 'false');
}
} catch (error) {
console.error('Error handling notification permissions:', error);
}
};
// Add these new functions
const saveNotificationsToStorage = async (notifs) => {
try {
await saveProgress('notifications', JSON.stringify(notifs));
} catch (error) {
console.error('Error saving notifications:', error);
}
};
const loadNotificationsFromStorage = async () => {
try {
const savedNotifications = await getProgress('notifications');
if (savedNotifications) {
const parsedNotifications = JSON.parse(savedNotifications);
setNotifications(parsedNotifications);
//add by amisha start
const relevantNotifications = filterNotificationsByRegion(parsedNotifications, userRegionId, language);
updateUnreadCountFromFiltered(relevantNotifications);
//add by amisha end
}
} catch (error) {
console.error('Error loading notifications:', error);
}
};
useEffect(() => {
requestPermissions();
getUserRegion();
loadNotificationsFromStorage();
const pusher = new Pusher('my pusher id', {
cluster: 'ap2',
});
const channel = pusher.subscribe('items');
channel.bind('items', async (event) => {
//console.log('Raw event received:', event);
try {
if (!event || !event.message) {
// console.log('Invalid event structure: Event or message is missing');
return;
}
const messageStr = event.message.replace(/\[\[|\]\]/g, '');
// console.log('Processed message string:', messageStr);
const languageEntries = messageStr.split('] [').map(entry => {
const [langPart, ...rest] = entry.split(' : ');
const contentPart = rest.join(' : ').trim();
const contentMatches = {
text: contentPart.match(/'([^']*)'/) ? contentPart.match(/'([^']*)'/)[1] : '',
slug: contentPart.match(/slug: '([^']*)'/) ? contentPart.match(/slug: '([^']*)'/)[1] : '',
id: contentPart.match(/id: '([^']*)'/) ? contentPart.match(/id: '([^']*)'/)[1] : '',
regions: contentPart.match(/regions: (\[[^\]]*\])/) ? JSON.parse(contentPart.match(/regions: (\[[^\]]*\])/)[1]) : [],
is_notified: contentPart.match(/is_notified: (\d+)/) ? parseInt(contentPart.match(/is_notified: (\d+)/)[1]) : 1,
};
return {
lang: langPart.trim(),
...contentMatches,
};
});
const regionIdInStorage = await getProgress('region');
//add by amisha start
const currentUserRegionId = regionIdInStorage ? parseInt(regionIdInStorage) : null;
//add by amisha end
languageEntries.forEach(entry => {
const isRegionMatch =
//add by amisha start
event.type === 1
? (entry.regions.length === 0 && currentUserRegionId === null) ||
(entry.regions.length > 0 && (entry.regions.includes(currentUserRegionId) || currentUserRegionId === null))
: event.type === 2
? entry.regions.length > 0 && entry.regions.includes(currentUserRegionId)
: false;
//add by amisha end
if (
entry.lang === language &&
entry.is_notified === 0 &&
isRegionMatch
) {
const newNotification = {
id: entry.id,
title: entry.text,
slug: entry.slug,
regions: entry.regions,
timestamp: new Date(),
read: false,
lang: language,
};
//add by amisha start
setNotifications(prev => {
const isDuplicate = prev.some(
notif => notif.slug === newNotification.slug && notif.title === newNotification.title
);
if (!isDuplicate) {
showLocalNotification(newNotification.title);
const newNotifications = [newNotification, ...prev];
saveNotificationsToStorage(newNotifications);
// Calculate the new unread count
const relevantNotifications = filterNotificationsByRegion(newNotifications, currentUserRegionId, language);
const newUnreadCount = relevantNotifications.filter(n => !n.read).length;
setUnreadCount(newUnreadCount);
return newNotifications;
}
return prev;
});
}
});
// add by amisha end
} catch (error) {
console.error('Error processing notification:', error);
}
});
pusher.connection.bind('error', (err) => {
console.error('Pusher connection error:', err);
});
return () => {
pusher.unsubscribe('items');
};
}, [language, userRegionId]);
const showLocalNotification = async (title) => {
try {
await Notifications.scheduleNotificationAsync({
content: {
title: t('New') + 'Notification',
body: title,
},
trigger: null,
});
} catch (error) {
console.error('Error showing notification:', error);
}
};
return (
{
const updatedNotifications = notifications.map(n => ({ ...n, read: true }));
setNotifications(updatedNotifications);
saveNotificationsToStorage(updatedNotifications);
setUnreadCount(0);
},
setNotifications: (newNotifications) => {
setNotifications(newNotifications);
saveNotificationsToStorage(newNotifications);
const relevantNotifications = filterNotificationsByRegion(newNotifications, userRegionId, language);
updateUnreadCountFromFiltered(relevantNotifications);
}
}}
>
);
};
< /code>
Code Service Code
notification.php
Подробнее здесь: https://stackoverflow.com/questions/796 ... ot-working