Как может usernotificationCenter (_: didReceive :) вызвать сбой даже без ничего в теле функции?IOS

Программируем под IOS
Ответить
Anonymous
 Как может usernotificationCenter (_: didReceive :) вызвать сбой даже без ничего в теле функции?

Сообщение Anonymous »

У меня есть приложение с уведомлениями, которые имеют уведомления. В течение многих лет все хорошо сработало, используя класс, который соответствует unusernotificationcenterdelegate и обработку действий в своем методе пользователя (_: DidReceive: withComplotionHandler) . В результате я переключился на асинхронную версию метода делегата, UsernotificationCenter (_: DidReceive :) Async , который больше не использует обработчик завершения. Вот пример, с удаленным именем приложения: < /p>

Код: Выделить всё

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Triggered by Thread:  16

Application Specific Information:
abort() called

Last Exception Backtrace:
0   CoreFoundation                         0x197ba2248 __exceptionPreprocess + 164
1   libobjc.A.dylib                        0x190f63a68 objc_exception_throw + 60
2   Foundation                             0x19252281c _userInfoForFileAndLine + 0
3   UIKitCore                              0x19aa4fe94 -[UIApplication _performBlockAfterCATransactionCommitSynchronizes:] + 404
4   UIKitCore                              0x19aa5c20c -[UIApplication _updateStateRestorationArchiveForBackgroundEvent:saveState:exitIfCouldNotRestoreState:updateSnapshot:windowScene:] + 528
5   UIKitCore                              0x19aa5c4d0 -[UIApplication _updateSnapshotAndStateRestorationWithAction:windowScene:] + 144
6                                          0x1006c36a8 @objc closure #1 in NotificationDelegate.userNotificationCenter(_:didReceive:) + 132
7                                          0x1006c37d1 partial apply for @objc closure #1 in NotificationDelegate.userNotificationCenter(_:didReceive:) + 1
8                                          0x10049d845 thunk for @escaping @callee_guaranteed @Sendable @async () -> () + 1
9                                          0x1005ceb3d thunk for @escaping @callee_guaranteed @Sendable @async () -> ()partial apply + 1
10                                         0x1005cea01 specialized thunk for @escaping @callee_guaranteed @Sendable @async () -> (@out A) + 1
11                                         0x1005cec75 partial apply for specialized thunk for @escaping @callee_guaranteed @Sendable @async () -> (@out A) + 1
12  libswift_Concurrency.dylib             0x1a1dce2d1 completeTaskWithClosure(swift::AsyncContext*, swift::SwiftError*) + 1
На основе тестирования сбой происходит при принятии действий по уведомлению, например, нанести уведомление об открытии приложения (например (ответа на UnnotificationDefaultActionIdate ).
из метода делегата я передаю центр и ответ на метод, который обрабатывает обработку асинхронно. В попытке сузить проблему, я исключал одну часть за время из моего процесса -обращения (_: DidReceive :) Async Метод, пока у меня не осталось ничего, кроме как сводка печати:

Код: Выделить всё

func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse)
async
{
await processResponse(center,
response: response)
}

private func processResponse(_ center: UNUserNotificationCenter,
response: UNNotificationResponse)
async
{
print("Do almost nothing...")
}
< /code>
Даже этот минимальный пример результатов сбоя. Как я могу устранить это дальше, чтобы получить CenertificationCenter (_: DidReceive :) Async 
Метод, работающий без этих сбоев? В моем AppDelegate, прежде чем DidFinishLaUnchingWithoptions я настроил уведомление Controller (ответственное за настройку и планирование уведомлений), а затем уведомление (ответственное за действия действий) в качестве Lazy VAR, чтобы я мог передать уведомление -контроллер в уведомление:

Код: Выделить всё

private lazy var notificationController =
NotificationController(statsProvider: statsProvider)

private lazy var notificationDelegate: NotificationDelegate =
NotificationDelegate(
notificationController: notificationController
)
Затем, в didfinishlaunchingwithoptions , я устанавливаю делегат на UnusernotificationCenter.current () :

Код: Выделить всё

UNUserNotificationCenter.current().delegate = notificationDelegate
< /code>
Я не думаю, что какая -либо настройка является ненормальной, если я не упускаю что -то, поэтому я не могу видеть, как почти пустой метод делегата все еще может сбои. Я хотел бы знать правильный способ использования CenertiationCenter (_: DidReceive :) Async 
метод делегирования без сбоя.
Это простое приложение отправляет уведомление через 5 секунд после его запуска. Нажатие уведомления, чтобы открыть приложение, должно планировать еще одно уведомление через 5 секунд, но приложение снимается. Вот AppDelegate: < /p>

Код: Выделить всё

import UIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

private lazy var notificationController = NotificationController()

private lazy var notificationDelegate = NotificationDelegate(
notificationController: notificationController
)

func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?)
-> Bool
{
UNUserNotificationCenter.current().delegate = notificationDelegate

return true
}

// MARK: UISceneSession Lifecycle

func application(_ application: UIApplication,
configurationForConnecting connectingSceneSession: UISceneSession,
options: UIScene.ConnectionOptions)
-> UISceneConfiguration
{
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
}
< /code>
notificationController: < /p>
import UserNotifications

class NotificationController {

init()
{
Task {
await setUpPermissions()
}
}

func scheduleNotification()
async
{
let content = UNMutableNotificationContent()
content.body = "Test notification"
content.sound = .default

let trigger = UNTimeIntervalNotificationTrigger(
timeInterval: 5,
repeats: false
)

let request = UNNotificationRequest(
identifier: "Test",
content: content,
trigger: trigger
)

do {
try await UNUserNotificationCenter.current()
.add(request)
}
catch {
print(error.localizedDescription)
}
}

private func setUpPermissions()
async
{
let authorizationStatus = await UNUserNotificationCenter.current()
.notificationSettings()
.authorizationStatus

switch authorizationStatus {

case .notDetermined:

do {
let granted = try await UNUserNotificationCenter.current()
.requestAuthorization(options: [.sound, .alert])

if granted
{
await scheduleNotification()
}
}
catch { print(error.localizedDescription) }

case .authorized:

await scheduleNotification()

default:
break
}
}
}
< /code>
natificationDelegate: < /p>
import UserNotifications

class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {

private let notificationController: NotificationController

init(notificationController: NotificationController)
{
self.notificationController = notificationController
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification)
async -> UNNotificationPresentationOptions
{
return [.banner, .sound]
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse)
async
{
print("didReceive response")

if response.actionIdentifier == UNNotificationDefaultActionIdentifier
{
await notificationController.scheduleNotification()
}
}
}
< /code>
Обратите внимание, что это даже сбои без попытки назначить другое уведомление: < /p>
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse)
async
{
print("didReceive response")
}
Как можно правильно использовать этот пользовательский центр (_: didReceive :) Async , чтобы избежать сбоя?

Подробнее здесь: https://stackoverflow.com/questions/737 ... nothing-in
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»