首页 > 解决方案 > 如何正确实现 didFinishNavigation

问题描述

我正在尝试在 didFinishNavigation 上实现一段代码,该代码段在 webview 中调用 js 函数。但似乎我没有正确实现这一点。

#import "DummyWebView.h"
#import "DummyOptions.h"
#import <WebKit/WebKit.h>


@implementation DummyWebView


- (void)viewDidLoad {
    [super viewDidLoad];
    CGRect screen = [[UIScreen mainScreen] bounds];
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(screen), CGRectGetHeight(screen))];
    NSString *urlString = @"https://5e9dad3079f67.htmlsave.net";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
    [self.view addSubview:webView];
}

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSString *json = [NSString stringWithFormat:@"%s %s %s %s %s %s", "{", "\"status\" :",  "\"", "bassey", "\"","}"];

NSString *function = [NSString stringWithFormat:@"%s %@ %s", "test('", json, "')"];

[webView evaluateJavaScript:function completionHandler:^(NSString *result, NSError *error)
{
    NSLog(@"Error %@",error);
    NSLog(@"Result %@",result);
}];
}

- (void)viewDidAppear:(BOOL)animated{
    NSLog(@"viewDidAppear loaded successfully");
}

@end

请问我做错了什么?

标签: iosobjective-c

解决方案


我刚刚得到这个工作。回到 Objective-C 有点受创!

在你的头文件中:

#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>

@interface ViewController : UIViewController <WKNavigationDelegate>


@end

您需要在WebKit此处导入并让您ViewController符合WKNavigationDelegate.

在方法文件中:

WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(screen), CGRectGetHeight(screen))];
webView.navigationDelegate = self;

使用委托集,它现在将调用该函数:

在此处输入图像描述


推荐阅读