Я разрабатываю приложение для iOS Native, которое использует живую деятельность. Я реализовал функциональность живых действий с использованием нативных модулей (Objective-C/Swift) для взаимодействия с базовыми APIS iOS. Обновления живой активности запускаются с помощью APN Push -уведомлений. Иногда, когда я отправляю push -уведомление, живая деятельность правильно обновляется и отображает новую информацию. В других случаях появляется уведомление (я вижу его в журналах консоли или используя инструмент тестирования уведомлений push), но живая деятельность остается неизменной. Не существует последовательного шаблона, когда обновления преуспевают или не проходят. > Полезная нагрузка включает в себя необходимый словарь APS с подготовленным контентом клавиш, установленным на 1, и я также включаю ключ Alert для тестирования (хотя я понимаю, что это не требуется строго для фонового обновления). Я подтвердил, что устройство достоверно получает уведомление о PHIP. Тщательно просмотрел нативный код модуля, который обрабатывает обновления живой деятельности. Я использую Activity.Update для обновления атрибутов действия. Я добавил журнал в натуральный модуль, чтобы подтвердить, что функция обновления вызывается, когда получает уведомление о push. Журналы показывают, что функция является , даже когда живая деятельность не обновляется, предполагая, что проблема может быть связана с Activity.Update Call или чем -то, что связано с временем Обновление.
фоновые режимы: Я включил возможность «фоновые режимы» в XCode для моего приложения, В частности, параметры «Фоно -избрать» и «удаленные уведомления». Я тестировал как на физических устройствах, так и на симуляторах, работающих на разных версиях iOS, но прерывистое поведение сохраняется. < /P>
messaging().setBackgroundMessageHandler(async (remoteMessage) => {
console.log('Notification.js: Your message was handled in background');
if (DynamicIslandModule && Platform.OS === "ios" && Platform.Version >= 16.1) {
console.log("Notification.js true", remoteMessage);
console.log(DynamicIslandModule, 'DynamicIslandModule');
console.log(remoteMessage?.data?.order, 'order id from background notification');
if (["void", "cancel", "bad", "complete"].includes(remoteMessage?.data?.title.toLowerCase())) {
await DynamicIslandModule.endNotificationActivity();
} else {
await DynamicIslandModule.updateNotificationActivityWithOrderStatus(
remoteMessage?.data?.message,
remoteMessage?.data?.order
);
}
}
if (remoteMessage?.data?.notificationId) {
console.log('Your message was handled in background');
let notificationId = remoteMessage?.data?.notificationId;
await store.getLastSavedToken();
await singleton.markNotificationReceived({ _id: notificationId });
console.log(
'Message handled in the background!',
remoteMessage?.data?.notificationId
);
}
});
< /code>
< /li>
//DynamicIslandModule.swift
@objc(updateNotificationActivityWithOrderStatus:withOrderID:withOrderMessage:withTitle:withResolve:withReject:)
func updateNotificationActivity(
orderStatus: NSString,
orderID: NSString,
orderMessage: NSString,
title: NSString,
resolve: @escaping RCTPromiseResolveBlock,
reject: @escaping RCTPromiseRejectBlock
) {
let status = orderStatus as String
let orderIDString = orderID as String
guard let storedIDs = UserDefaults.standard.array(forKey: "liveActivityIDs") as? [String],
storedIDs.contains(orderIDString) else {
print("ERROR: Live Activity ID not found in UserDefaults")
return
}
guard let liveActivity = Activity.activities.first(where: { activity in
if let contentState = activity.contentState as? NotificationAttributes.ContentState {
return contentState.orderID == orderIDString
}
return false
}) else {
print("ERROR: Live Activity not found for ID: \(orderIDString)")
return
}
guard let currentContentState = liveActivity.contentState as? NotificationAttributes.ContentState else {
print("ERROR: Failed to retrieve current content state")
return
}
let updatedContentState = NotificationAttributes.ContentState(
orderStatus: status,
orderID: orderIDString,
pickupLocation: currentContentState.pickupLocation,
dropoffLocation: currentContentState.dropoffLocation,
serviceMethod: currentContentState.serviceMethod,
orderMessage: orderMessage as String,
title: title as String
)
if #available(iOS 16.1, *) {
print("Updating Live Activity...")
Task {
do {
try await liveActivity.update(using: updatedContentState)
resolve("Live Activity updated successfully for order #\(orderIDString)")
print("Live Activity updated successfully for order #\(orderIDString) status:\(status)")
} catch let error {
reject("ERROR", "Failed to update live activity", error)
print("Error updating live activity: \(error.localizedDescription)")
}
}
} else {
reject("ERROR", "iOS version not supported", nil)
}
}
< /code>
< /li>
//AppDelegate.mm
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
if (@available(iOS 16.1, *)) {
NSString *orderID = userInfo[@"data"][@"order"];
NSString *orderMessage = userInfo[@"data"][@"message"];
NSString *orderStatus = userInfo[@"data"][@"status"];
NSString *orderTitle = userInfo[@"data"][@"title"];
NSLog(@"didReceiveRemoteNotification triggered");
NSArray *endTitles = @[@"complete", @"void", @"bad", @"cancel"];
if ([endTitles containsObject:orderStatus.lowercaseString]) {
[LiveActivityHelper endActivityWithIdWithOrderID:orderID];
} else {
[LiveActivityHelper updateActivityWithOrderID:orderID orderStatus:orderStatus orderMessage:orderMessage title:orderTitle];
}
completionHandler(UIBackgroundFetchResultNewData);
} else {
completionHandler(UIBackgroundFetchResultNewData);
}
}
< /code>
< /li>
< /ul>
Вопрос: < /p>
Что может вызвать эти прерывистые обновления живой деятельности? Существуют ли какие -либо конкретные соображения, касающиеся времени, выполнения фоновых или структуры полезной нагрузки APNS, которые я мог бы пропустить? Любые предложения по отладке этого дальнейшего>
Подробнее здесь: https://stackoverflow.com/questions/794 ... -sometimes
## Проблема с обновлением активности в React Native * Название: * Живая деятельность иногда обновления иногда не обновля ⇐ IOS
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение