Objective- C: getNotificationSettingsWithCompletionHandler назначить переменной из обработчика завершения. Как? - PullRequest
0 голосов
/ 17 марта 2020

У меня сложилась очень простая проблема. В последнее время много не использовал Objective- C. Может ли кто-нибудь помочь мне с:

+(UNAuthorizationStatus) mCheckPermissions {

__block UNAuthorizationStatus oOutput = 0;

UNUserNotificationCenter* oCenter = [UNUserNotificationCenter currentNotificationCenter];
[oCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
    oOutput = settings.authorizationStatus;
}];

return oOutput;
}

Мне нужно присвоить значение oOutput из обработчика завершения. Пока это неправильно оценивает ценность. Что мне не хватает? И, пожалуйста, не отвечайте мне что-то связанное со Свифтом. Вопрос об Objective- C.

Ответы [ 2 ]

0 голосов
/ 18 марта 2020

Решение найдено. Вопрос закрыт.

+(UNAuthorizationStatus) mCheckPermissions {

__block UNAuthorizationStatus oOutput = UNAuthorizationStatusNotDetermined;
dispatch_semaphore_t oSemaphore = dispatch_semaphore_create(0);

UNUserNotificationCenter* oCenter = [UNUserNotificationCenter currentNotificationCenter];
[oCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
    oOutput = settings.authorizationStatus;
    dispatch_semaphore_signal(oSemaphore);
}];

if (![NSThread isMainThread]) {
    dispatch_semaphore_wait(oSemaphore,DISPATCH_TIME_FOREVER);
} else {
    while (dispatch_semaphore_wait(oSemaphore,DISPATCH_TIME_NOW)) {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0]];
    }
}

return oOutput;
}
0 голосов
/ 17 марта 2020

Что вам не хватает, так это то, что getNotificationSettingsWithCompletionHandler является асинхронным.

Это означает, что «ответ» в блоке (ваш settings.authorizationStatus) возвращается к вам после завершен весь метод mCheckPermissions, включая return. Порядок выполнения таков:

+(UNAuthorizationStatus) mCheckPermissions {

    __block UNAuthorizationStatus oOutput = 0;

    /* 1 */ UNUserNotificationCenter* oCenter = [UNUserNotificationCenter currentNotificationCenter];
    /* 2 */ [oCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        /* 4 */ oOutput = settings.authorizationStatus;
    }];
    /* 3 */ return oOutput;
}


Поэтому невозможно вернуть из внешнего метода mCheckPermissions значение, которое поступает в блок. (Если только у вас нет машины времени в вашем кармане, вы можете заглянуть в будущее и узнать, каков будет результат .)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...