Понимание definePolicyForNavigationResponse с взаимодействием с пользователем - PullRequest
0 голосов
/ 11 февраля 2019

Я хотел бы получить одобрение пользователя перед открытием ссылки с помощью WKWebView.(Задача C) Я использую definePolicyForNaviagationResponse.

Когда он встречает ссылку в HTML, он должен спросить с помощью UIAlertController, нормально ли переходить по ссылке или нет (в простейшей реализации).

Однако, похоже, что он работает асинхронно, поэтому сначала он открывает ссылку, а затем, в конце концов, находит сообщение.

Как мне найти ссылку, всплыть предупреждение и ТОлибо открой ссылку, либо нет.Я предполагаю, что-то о блоках, которые я не понимаю, как обработчик завершения, или, возможно, использование семафоров, хотя мои скромные попытки их не сработали.

Я упростил код, чтобы было понятно, чтопроисходит.

Спасибо!

static bool launchPermission = false;
@property (strong, nonatomic) WKWebViewConfiguration *theConfiguration;
@property (strong, nonatomic) WKWebView *webView;

.
.
.

_webView.navigationDelegate = self;
[_webView  loadRequest:nsrequest];
[self.view addSubview:_webView];

.
.
.

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{

        [self askPermissionForExternalLink];
        if (launchPermission)
        {
            decisionHandler(WKNavigationResponsePolicyAllow);
        }
        else
        {
            decisionHandler(WKNavigationResponsePolicyCancel);
        }
}


- (void) askPermissionForExternalLink
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Open external Web Conten?" message:@"Link is embedded with other content" preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *cancelAction = [UIAlertAction
                                   actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel action")
                                   style:UIAlertActionStyleCancel
                                   handler:^(UIAlertAction *action)
                                   {
                                       NSLog(@"Cancel action");
                                       [self cancelMethod];
                                       //return;
                                   }];

    UIAlertAction *okAction = [UIAlertAction
                               actionWithTitle:NSLocalizedString(@"OK", @"OK action")
                               style:UIAlertActionStyleDefault
                               handler:^(UIAlertAction *action)
                               {
                                   NSLog(@"OK action");
                                   //[self launchURL];
                                   [self OKMethod];
                               }];

    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [alert show];
}

- (bool) cancelMethod
{
    launchPermission = false;
    return false;   
}

- (bool) OKMethod
{
    launchPermission = true;
    return true;    
}

1 Ответ

0 голосов
/ 16 февраля 2019

Вы можете попробовать это таким образом, используя сначала блоки в decidePolicyForNavigationResponse make defineAction внутри блока

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{



       void (^ launchPermission)(BOOL) = ^(BOOL isAllow)
        {
            if(isAllow)
            {
                decisionHandler(WKNavigationActionPolicyAllow);
            }
            else
            {
                decisionHandler(WKNavigationActionPolicyCancel);
            }
            return;
        };
        [self askPermissionForExternalLink];

    }

здесь на основе выбора пользователя отправьте ДА или НЕТ в блок launchPermission

- (void) askPermissionForExternalLink
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Open external Web Conten?" message:@"Link is embedded with other content" preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *cancelAction = [UIAlertAction
                                   actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel action")
                                   style:UIAlertActionStyleCancel
                                   handler:^(UIAlertAction *action)
                                   {
                                       NSLog(@"Cancel action");
                                       launchPermission(NO);
                                       return;
                                   }];

    UIAlertAction *okAction = [UIAlertAction
                               actionWithTitle:NSLocalizedString(@"OK", @"OK action")
                               style:UIAlertActionStyleDefault
                               handler:^(UIAlertAction *action)
                               {
                                   NSLog(@"OK action");

                                   launchPermission(YES);
                                  return ;
                               }];

    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [alert show];
}
...