IT TIP

WKWebView로 마이그레이션하는 방법?

itqueen 2020. 12. 10. 21:35
반응형

WKWebView로 마이그레이션하는 방법?


iOS8에서 새로운 WKWebView를 사용하는 방법을 이해하려고하는데 많은 정보를 찾을 수 없습니다. 나는 읽었다 :

http://developer.telerik.com/featured/why-ios-8s-wkwebview-is-a-big-deal-for-hybrid-development/ http://nshipster.com/wkwebkit/

하지만 이것이 기존 앱에 어떤 영향을 미칠까요? 일반 UiWebView가 니트로 자바 스크립트 엔진에서 속도를 높일 수 있습니까? 아니면 변경해야합니까? 이전 버전과의 호환성을 어떻게 처리합니까?

내가 찾을 수있는 모든 코드와 예제는 swift를 사용하고 있습니다. 이것이 필수입니까?

이 문제에 대한 도움에 감사드립니다!


UIWebView기존 앱에서 계속 작동합니다. WKWebView에서 사용할 수 있으며 Nitro JavaScript 엔진 iOS8WKWebView있습니다.

오래된 애플 리케이션이 빠른 자바 스크립트 엔진을 활용하려면 코드를 변경 사용할 수 있도록 할 필요가 WKWebView대신 UIWebView. 들어 iOS7세 이상, 당신은 계속 사용할 필요가 UIWebView당신을 위해 확인해야 할 수도 있으므로, iOS8다음 적용 WKWebView에 대체 방법 / 대리자 메서드 및 UIWebView방법 iOS7세. 또한 WKWebView(아직)에 대한 인터페이스 빌더 구성 요소가 없으므로 프로그래밍 방식으로 WKWebView.

WKWebViewObjective-C에서 구현할 수 있습니다 . 다음은 다음을 시작하는 간단한 예입니다 WKWebView.

WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:theConfiguration];
webView.navigationDelegate = self;
NSURL *nsurl=[NSURL URLWithString:@"http://www.apple.com"];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[webView loadRequest:nsrequest];
[self.view addSubview:webView];

WKWebView렌더링 성능은 WebGL 게임과 복잡한 JavaScript 알고리즘을 실행하는 것에서 눈에 띄게 나타납니다. webview를 사용하여 간단한 html 또는 웹 사이트를로드하는 경우 UIWebView.

다음은 또는 중 하나를 사용하여 웹 사이트를 여는 데 사용할 수 있는 테스트 입니다. 성능을 비교 한 다음 사용할 앱 업그레이드를 결정할 수 있습니다 . https://itunes.apple.com/app/id928647773?mt=8&at=10ltWQUIWebViewWKWebViewWKWebView

여기에 이미지 설명 입력


UIWebView 에서 WKWebView로 전환 한 방법은 다음과 같습니다 .

참고 : 스토리 보드로 드래그 할 수있는 UIWebView와 같은 속성은 없으며 프로그래밍 방식으로 수행해야합니다.

WebKit / WebKit.h 를 헤더 파일로 가져와야 합니다.

이것은 내 헤더 파일입니다.

#import <WebKit/WebKit.h>

@interface ViewController : UIViewController

@property(strong,nonatomic) WKWebView *webView;
@property (strong, nonatomic) NSString *productURL;

@end

내 구현 파일은 다음과 같습니다.

#import "ViewController.h"

@interface ViewController ()

@end


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.productURL = @"http://www.URL YOU WANT TO VIEW GOES HERE";

    NSURL *url = [NSURL URLWithString:self.productURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    _webView = [[WKWebView alloc] initWithFrame:self.view.frame];  
    [_webView loadRequest:request];
    _webView.frame = CGRectMake(self.view.frame.origin.x,self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height);
    [self.view addSubview:_webView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

단계 : 1 가져 오기webkitViewController.swift

import WebKit

Step : 2 webView의 변수를 선언합니다.

var webView : WKWebView!

단계 : 3 대리인 추가WKNavigationDelegate

class ViewController: UIViewController , WKNavigationDelegate{

단계 : 4 의 코드를 추가ViewDidLoad.

let myBlog = "https://iosdevcenters.blogspot.com/"
let url = NSURL(string: myBlog)
let request = NSURLRequest(URL: url!)

// init and load request in webview.
webView = WKWebView(frame: self.view.frame)
webView.navigationDelegate = self
webView.loadRequest(request)
self.view.addSubview(webView)
self.view.sendSubviewToBack(webView)

단계 : 5info.plist 추가편집

<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>google.com</key>
<dict>
    <key>NSExceptionAllowsInsecureHTTPLoads</key>
    <true/>
    <key>NSIncludesSubdomains</key>
    <true/>
</dict>
</dict>

Swift는 필수 사항이 아니며 모든 것이 Objective-C에서 잘 작동합니다. UIWebView는 계속 지원되므로 시간을내어 마이그레이션을 서두르지 않아도됩니다. 그러나 WKWebView의 javascript 및 스크롤 성능 향상을 얻지 못합니다.

이전 버전과의 호환성을 위해 뷰 컨트롤러에 UIWebView와 WKWebView라는 두 가지 속성이 있습니다. 클래스가 존재하는 경우에만 WKWebview를 사용합니다.

if ([WKWebView class]) {
    // do new webview stuff
} else {
    // do old webview stuff
}

이전에는 UIWebViewDelegate가 있었지만 WKNavigationDelegate로 만들고 필요한 메서드를 만들었습니다.


WkWebView는 Apple 문서 에 따르면 UIWebview보다 훨씬 빠르고 안정적 입니다. 여기에 WkWebViewController를 게시했습니다.

import UIKit
import WebKit

class WebPageViewController: UIViewController,UINavigationControllerDelegate,UINavigationBarDelegate,WKNavigationDelegate{

    var webView: WKWebView?
    var webUrl="http://www.nike.com"

    override func viewWillAppear(animated: Bool){
        super.viewWillAppear(true)
        navigationController!.navigationBar.hidden = false

    }
    override func viewDidLoad()
    {
        /* Create our preferences on how the web page should be loaded */
        let preferences = WKPreferences()
        preferences.javaScriptEnabled = false

        /* Create a configuration for our preferences */
        let configuration = WKWebViewConfiguration()
        configuration.preferences = preferences

        /* Now instantiate the web view */
        webView = WKWebView(frame: view.bounds, configuration: configuration)

        if let theWebView = webView{
            /* Load a web page into our web view */
            let url = NSURL(string: self.webUrl)
            let urlRequest = NSURLRequest(URL: url!)
            theWebView.loadRequest(urlRequest)
            theWebView.navigationDelegate = self
            view.addSubview(theWebView)

        }


    }
    /* Start the network activity indicator when the web view is loading */
    func webView(webView: WKWebView,didStartProvisionalNavigation navigation: WKNavigation){
            UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    }

    /* Stop the network activity indicator when the loading finishes */
    func webView(webView: WKWebView,didFinishNavigation navigation: WKNavigation){
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
    }

    func webView(webView: WKWebView,
        decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse,decisionHandler: ((WKNavigationResponsePolicy) -> Void)){
            //print(navigationResponse.response.MIMEType)
            decisionHandler(.Allow)

    }
    override func didReceiveMemoryWarning(){
        super.didReceiveMemoryWarning()
    }

}

iOS 8에서 Swift를 사용하는 WKWebView.

The whole ViewController.swift file now looks like this:

import UIKit
import WebKit

class ViewController: UIViewController {

    @IBOutlet var containerView : UIView! = nil
    var webView: WKWebView?

    override func loadView() {
        super.loadView()

        self.webView = WKWebView()
        self.view = self.webView!
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var url = NSURL(string:"http://www.kinderas.com/")
        var req = NSURLRequest(URL:url)
        self.webView!.loadRequest(req)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Use some design patterns, you can mix UIWebView and WKWebView. The key point is to design a unique browser interface. But you should pay more attention to your app's current functionality, for example: if your app using NSURLProtocol to enhance network ability, using WKWebView you have no chance to do the same thing. Because NSURLProtocol only effects the current process, and WKWebView using muliti-process architecture, the networking staff is in a seperate process.


You have to use WKWebView, which is available as of iOS8 in Framework 'WebKit' to get the speedup. If you need backwards compatibility, you have to use UIWebView for iOS7 and older.

I set up a little code to provide the UIViewController frame for the new WKWebView. It can be installed via cocoapods. Have a look here:

STKWebKitViewController on github


스위프트 4

    let webView = WKWebView()   // Set Frame as per requirment, I am leaving it for you
    let url = URL(string: "http://www.google.com")!
    webView.load(URLRequest(url: url))
    view.addSubview(webView)

참고 URL : https://stackoverflow.com/questions/25665141/how-to-migrate-to-wkwebview

반응형