LoginSignup
8
9

More than 5 years have passed since last update.

WKWebView Objective-C版サンプル

Posted at

まとまった記事が意外となかったので。

宣言

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

@interface MyWebView : UIView <WKNavigationDelegate, WKUIDelegate>
@property (strong) WKWebView *webView;
@end

初期化

MyWebView.m
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)];
_webView.navigationDelegate = self;
_webView.UIDelegate = self;
[self addSubview:_webView];

ロード

MyWebView.m
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];

進む、戻る、リロード

MyWebView.m
[_webView canGoBack];
[_webView canGoForward];
[_webView reload];
[_webView goForward];
[_webView goBack];

デリゲート

shouldStartLoadWithRequest

MyWebView.m
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation;

didStartLoad

MyWebView.m
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation;

didFinishLoad

MyWebView.m
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;

didFailWithError

MyWebView.m
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error;

Basic認証

UIAlertControllerWrapperはUIAlertControllerをラップしたクラスです。
こちらを参考に作りました。

MyWebView.m
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(nonnull NSURLAuthenticationChallenge *)challenge completionHandler:(nonnull void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
    if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic] == YES){ 
        NSLog(@"didReceiveAuthenticationChallenge");

        [UIAlertControllerWrapper showAlertViewWithIdAndPassword:@"Authentication" message:@"Input username and password." ok:^(UIAlertAction *action, UIAlertController *cntr){
            NSURLCredential *credential = [NSURLCredential credentialWithUser:[cntr.textFields objectAtIndex:0].text password:[cntr.textFields objectAtIndex:1].text persistence:NSURLCredentialPersistenceForSession];
            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);

        }cancel:^(UIAlertAction *cancel){
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        }];
    }else{
        completionHandler(NSURLSessionAuthChallengeRejectProtectionSpace, nil);
    }
}

Javascript実行

MyWebView.m
[webView evaluateJavaScript:@"document.title"
          completionHandler:^(NSString *result, NSError *error){
}];
8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9