首页 > 解决方案 > 如何使用 WebView 迁移代码以改用 WKWebview (macOS)?

问题描述

我一直在尝试更新以下代码,以便它使用 WKWebView 而不是现在已弃用的 macOS 上的 WebView。它是一个简单的程序,用于在 macOS 上将网页作为屏幕保护程序查看:

#import "WSView.h"
#import <WebKit/WebKit.h>

@implementation WSView

- (id)initWithFrame:(NSRect)frame isPreview:(BOOL)isPreview {
  if (!(self = [super initWithFrame:frame isPreview:isPreview])) return nil;

  NSURL* indexHTMLDocumentURL = [NSURL URLWithString:[[[NSURL fileURLWithPath:[[NSBundle bundleForClass:self.class].resourcePath stringByAppendingString:@"/index.html"] isDirectory:NO] description] stringByAppendingFormat:@"?screensaver=1%@", self.isPreview ? @"&is_preview=1" : @""]];

  WebView* webView = [[WebView alloc] initWithFrame:NSMakeRect(0, 0, frame.size.width, frame.size.height)];
  webView.frameLoadDelegate = self;
  webView.drawsBackground = NO; // Avoids a "white flash" just before the index.html file has loaded
  [webView.mainFrame loadRequest:[NSURLRequest requestWithURL:indexHTMLDocumentURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]];
  [self addSubview:webView];
  
  return self;
}

#pragma mark - ScreenSaverView

- (void)animateOneFrame { [self stopAnimation]; } // We don't need animation callbacks
- (BOOL)hasConfigureSheet { return NO; } // Nothing to configure

#pragma mark - WebFrameLoadDelegate

- (void)webView:(WebView *)sender didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame {
  NSLog(@"%@ error=%@", NSStringFromSelector(_cmd), error);
}

@end

在 Xcode 中编译代码时出现的警告消息是:

'WebView' 已弃用:在 macOS 10.14 中首次弃用 - 不再受支持;请采用 WKWebView。

'WebFrame' 已弃用:首先在 macOS 10.14 中弃用

'从不兼容的类型'WSView *__strong'分配给'id'

我想更新它以确保它可以在未来版本的 macOS 上运行,但不幸的是我没有这样做的编码技能。谁能指出我正确的方向?谢谢。

标签: webviewwkwebview

解决方案


推荐阅读