您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

WKWebView 與 JS 交互實戰:取得系統圖片、Alert/Confirm/TextInput 代理與屏蔽默認菜單

編輯:iOS 開發綜合

最近參與的專案一開始用的是 UIWebView 與 JS 交互,但它在記憶體管理上表現不佳,因此改用 WKWebView——記憶體與線程管理都更好。當然 WKWebView 也有代價:它載入的 H5 頁面不支援 ajax 請求,所有網路請求都得在原生端自己實作。

一、幾個要先注意的問題

1. 若要取得相機或相簿的圖片,iOS 10 之後必須在 Info.plist 中宣告權限說明:

相機權限:Privacy - Camera Usage Description

相簿權限:Privacy - Photo Library Usage Description

2. UIWebView 與 WKWebView 和 JS 互調的方式、傳參型別都不同:

UIWebView:window.iosModel.getImage(JSON.stringify(parameter)),用 JSON.stringify 把物件序列化成字串傳給原生。

WKWebView:window.webkit.messageHandlers.iosModel.postMessage(parameter)。

3. 特別注意:WKWebView 不執行 JS 寫的 ajax 請求(它基於 WebKit,不會處理 C socket 相關的 HTTP 請求),有網路需求時必須用 Objective-C 自己實作。

4. 別忘了在 interface 中宣告 WKScriptMessageHandler、UIImagePickerControllerDelegate 等代理。

5. 屏蔽 WebView 的默認可選菜單(避免出現拷貝、全選等彈出菜單),可在頁面載入完成的回調中執行兩段 JS:

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    NSLog(@"66===%s", __FUNCTION__);
    // 禁用選中與長按菜單
    [self.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none'"
                   completionHandler:nil];
    [self.webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none'"
                   completionHandler:nil];
}

二、完整程式碼

H5 頁面:

<input id="Button" onclick="getIOSImage()" type="button" value="開啟相機取得圖片" />
<img id="changeImage" src="" />
<div id="iosParame"></div>

<script>
var getIOSImage = function () {
    var parameter = { 'title': 'JS 調 OC', 'describe': '這裡是 JS 傳給 OC 的參數' };
    // WKWebView 的呼叫方式;JSON.stringify 把物件轉為字串
    window.webkit.messageHandlers.iosModel.postMessage(parameter);
};

// 供 OC 回呼叫用的方法
function setImageWithPath(arguments) {
    document.getElementById('changeImage').src = arguments['imagePath'];
    document.getElementById('iosParame').innerHTML = arguments['iosContent'];
}
</script>

原生端主要程式碼:

#import "ViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import <WebKit/WebKit.h>
#import "SaveImage_Util.h"

@interface ViewController () <WKScriptMessageHandler, UIImagePickerControllerDelegate>
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIProgressView *progressView;
@end

@implementation ViewController {
    int indextNumb;      // 交替使用的圖檔名序號
    UIImage *getImage;   // 取得的圖片
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.automaticallyAdjustsScrollViewInsets = NO;

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.preferences = [[WKPreferences alloc] init];
    config.preferences.minimumFontSize = 10;
    config.preferences.javaScriptEnabled = YES;
    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    config.processPool = [[WKProcessPool alloc] init];
    config.userContentController = [[WKUserContentController alloc] init];

    // 注入 JS 物件名 iosModel,JS 透過它呼叫時會走到 WKScriptMessageHandler 代理
    [config.userContentController addScriptMessageHandler:self name:@"iosModel"];

    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;

    NSURL *path = [[NSBundle mainBundle] URLForResource:@"testJS" withExtension:@"html"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:path]];
    [self.view addSubview:self.webView];

    // KVO 監聽載入狀態、標題與進度
    [self.webView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];

    self.progressView = [[UIProgressView alloc] initWithFrame:self.view.bounds];
    self.progressView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.progressView];

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"後退"
        style:UIBarButtonItemStyleDone target:self action:@selector(goback)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"前進"
        style:UIBarButtonItemStyleDone target:self action:@selector(gofarward)];
}

#pragma mark - WKScriptMessageHandler

// 接收 JS 傳來的資料(僅支援 NSNumber、NSString、NSDate、NSArray、NSDictionary、NSNull)
- (void)userContentController:(WKUserContentController *)userContentController
       didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"iosModel"]) {
        NSLog(@"JS 傳來的資料:%@", message.body);
        NSDictionary *jsDictionary = message.body;
        if ([jsDictionary[@"means"] isEqualToString:@"取得系統圖片"]) {
            [self beginOpenPhoto];
        }
    }
}

#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
                        change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"title"]) {
        self.title = self.webView.title;
    } else if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.webView.estimatedProgress;
    }
    if (!self.webView.loading) {
        [UIView animateWithDuration:0.5 animations:^{ self.progressView.alpha = 0; }];
    }
}

#pragma mark - WKNavigationDelegate

// 請求發出前攔截,可決定是否允許跳轉
- (void)webView:(WKWebView *)webView
    decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
                   decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSString *hostname = navigationAction.request.URL.host.lowercaseString;
    // 跨域的連結改用系統瀏覽器開啟
    if (navigationAction.navigationType == WKNavigationTypeLinkActivated
        && ![hostname containsString:@".lanou.com"]) {
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
        decisionHandler(WKNavigationActionPolicyCancel);
    } else {
        self.progressView.alpha = 1.0;
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

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

// 導航完成,頁面載入結束
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    // 屏蔽默認的選字與長按菜單
    [self.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none'"
                   completionHandler:nil];
    [self.webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none'"
                   completionHandler:nil];
}

// HTTPS 憑證驗證(若不做校驗,走預設即可)
- (void)webView:(WKWebView *)webView
    didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
                    completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler {
    completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}

#pragma mark - WKUIDelegate

// JS 呼叫 alert
- (void)webView:(WKWebView *)webView
    runJavaScriptAlertPanelWithMessage:(NSString *)message
                    initiatedByFrame:(WKFrameInfo *)frame
                   completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alert"
        message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault
        handler:^(UIAlertAction * _Nonnull action) { completionHandler(); }]];
    [self presentViewController:alert animated:YES completion:NULL];
}

// JS 呼叫 confirm,結果需透過 completionHandler 回傳給 JS
- (void)webView:(WKWebView *)webView
    runJavaScriptConfirmPanelWithMessage:(NSString *)message
                      initiatedByFrame:(WKFrameInfo *)frame
                     completionHandler:(void (^)(BOOL result))completionHandler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"confirm"
        message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault
        handler:^(UIAlertAction * _Nonnull action) { completionHandler(YES); }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
        handler:^(UIAlertAction * _Nonnull action) { completionHandler(NO); }]];
    [self presentViewController:alert animated:YES completion:NULL];
}

// JS 呼叫 prompt,輸入結果同樣要回傳
- (void)webView:(WKWebView *)webView
    runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt
                              defaultText:(nullable NSString *)defaultText
                         initiatedByFrame:(WKFrameInfo *)frame
                        completionHandler:(void (^)(NSString *))completionHandler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:prompt
        message:defaultText preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.textColor = [UIColor redColor];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault
        handler:^(UIAlertAction * _Nonnull action) {
            completionHandler([[alert textFields] lastObject].text);
        }]];
    [self presentViewController:alert animated:YES completion:NULL];
}

#pragma mark - 相機與相簿

- (void)beginOpenPhoto {
    dispatch_async(dispatch_get_main_queue(), ^{ [self takePhoto]; });
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)localPhoto {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.delegate = self;
    [self presentViewController:imagePicker animated:YES completion:nil];
}

- (void)takePhoto {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    } else {
        NSLog(@"模擬器無法開啟相機");
        [self localPhoto];   // 退回相簿
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker
    didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        getImage = [info objectForKey:UIImagePickerControllerOriginalImage];

        indextNumb = (indextNumb == 1) ? 2 : 1;
        NSString *nameStr = [NSString stringWithFormat:@"Varify%d.jpg", indextNumb];
        [SaveImage_Util saveImage:getImage ImageName:nameStr back:^(NSString *imagePath) {
            dispatch_async(dispatch_get_main_queue(), ^{
                // OC 回呼 JS:setImageWithPath 是 JS 中的全域函式,參數為物件
                NSString *callJSString = [NSString stringWithFormat:
                    @"setImageWithPath({\"imagePath\":\"%@\",\"iosContent\":\"取得圖片成功\"})", imagePath];
                [self.webView evaluateJavaScript:callJSString completionHandler:^(id result, NSError *error) {
                    NSLog(error ? @"OC 調 JS 失敗" : @"OC 調 JS 成功");
                }];
            });
        }];
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

@end

圖片存檔工具類:

// SaveImage_Util.h
@interface SaveImage_Util : NSObject
// 存檔案到 Documents/Images,並透過 back 回傳檔案路徑
+ (BOOL)saveImage:(UIImage *)saveImage
        ImageName:(NSString *)imageName
             back:(void(^)(NSString *imagePath))back;
@end
// SaveImage_Util.m
@implementation SaveImage_Util

+ (BOOL)saveImage:(UIImage *)saveImage ImageName:(NSString *)imageName
             back:(void(^)(NSString *imagePath))back {
    NSString *path = [SaveImage_Util getImageDocumentFolderPath];
    NSData *imageData = UIImagePNGRepresentation(saveImage);
    NSString *documentsDirectory = [NSString stringWithFormat:@"%@/", path];
    NSString *imageFile = [documentsDirectory stringByAppendingPathComponent:imageName];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:imageFile]) {
        // 已存在則先刪除再寫入
        if ([fileManager removeItemAtPath:imageFile error:nil]) {
            if ([imageData writeToFile:imageFile atomically:YES]) { back(imageFile); }
        }
    } else {
        if ([imageData writeToFile:imageFile atomically:NO]) {
            [fileManager createDirectoryAtPath:documentsDirectory
                  withIntermediateDirectories:YES attributes:nil error:nil];
            if ([imageData writeToFile:imageFile atomically:YES]) { back(imageFile); }
        } else {
            return YES;
        }
    }
    return NO;
}

+ (NSString *)getImageDocumentFolderPath {
    NSString *patchDocument = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                  NSUserDomainMask, YES) lastObject];
    return [NSString stringWithFormat:@"%@/Images", patchDocument];
}

@end

以上內容僅供參考,部分觀點來自社群討論。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved