Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
5
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@kz56cd

【iOS】UIWebViewでwebページ内のボタン等を制御する

経緯

該当画面はUIWebViewで表示した際、「閉じる」ボタンが効かなかった。
ボタン押下時は閉じるのではなく、一画面戻したかった為、方法を探った。

方法

jsを書き換える為のファイルを用意、プロジェクト内に格納:

JS_WebViewController.txt
window.close = function () {
    history.back();
};

window.close()history.back()で書き換えているだけ、シンプル。

次、
webViewDidFinishLoadで先のファイルを読込、書き換え:

WebViewController.m
// URL読込後
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSError *error = nil;
    NSString *jsFromFile = [NSString stringWithContentsOfURL:[[NSBundle mainBundle]
                                                              URLForResource:@"JS_WebViewController" withExtension:@"txt"]
                                                    encoding:NSUTF8StringEncoding error:&error];
    __unused NSString *jsOverrides = [webView
                                      stringByEvaluatingJavaScriptFromString:jsFromFile];
}

応用

urlスキーマ使えば、objC側でもっと自由にやれる:

JS_WebViewController.txt
window.close = function () {
    open("native://close");
};

同じくwebViewDidFinishLoadで書き換える:

WebViewController.m
- (void)webViewDidFinishLoad:(UIWebView *)webView {

    NSError *error = nil;
    NSString *jsFromFile = [NSString stringWithContentsOfURL:[[NSBundle mainBundle]
                                                              URLForResource:@"JS_WebViewController" withExtension:@"txt"]
                                                    encoding:NSUTF8StringEncoding error:&error];
    __unused NSString *jsOverrides = [webView stringByEvaluatingJavaScriptFromString:jsFromFile];


}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *scheme = [request.URL.scheme stringByAppendingString:@":"];
    scheme           = [scheme stringByAppendingString:request.URL.resourceSpecifier];
    if ([scheme isEqualToString:@"native://close"]) {

        /*
        *
        * Do Something!!!!!!!!!!!!!!!!!!
        *
        */

        [self dismissViewControllerAnimated:YES completion:nil];
        return NO;
    } else {
        return YES;
    }
}

スキーマはrequest.URL.schemerequest.URL.resourceSpecifierで取得して判定してる

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
5
Help us understand the problem. What are the problem?