Skip to content

Instantly share code, notes, and snippets.

@littilewing
Last active December 15, 2015 10:04
Show Gist options
  • Save littilewing/6b5e7eb600fe0a68b073 to your computer and use it in GitHub Desktop.
Save littilewing/6b5e7eb600fe0a68b073 to your computer and use it in GitHub Desktop.
//
// GeneralWebViewController.m
// eNAMO
//
// Created by Amon Keishima on 2015/11/10.
// Copyright © 2015年 Amon Keishima. All rights reserved.
//
//hayashi:optimizeWebPageは使ってません。
#import "GeneralWebViewController.h"
@interface GeneralWebViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>
@end
@implementation GeneralWebViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = _viewTitle;
NSInteger value = _webViewMode;
/**
* hayashi:
*/
NSString *code = @"$(\"#banner_area\").remove();$(\"#g_navi\").remove();$(\".g_navi01\").remove();$(\".g_navi02\").remove();$(\".g_navi03\").remove();$(\"#pankuzu\").remove();$(\"#inner_content_area_top\").remove();$(\"#inner_content_area_wrapper\").remove();$(\"#inner_content_area_btm\").remove();$(\"#footer\").remove();$(\"#header_navi\").remove();$(\"#logo\").remove();$(\"#wrapper\").css(\"width\",\"100%\");\
$(\"#right_area\").css(\"float\",\"none\");\
$(\"#right_area\").css(\"width\",\"100%\");$(\"#wrapper p:last\").remove();$('head').append('<meta name=\"viewport\" content=\"width=device-width\">');";
WKUserScript *script = [[WKUserScript alloc] initWithSource:code injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
WKUserContentController *ucont = [WKUserContentController new ];
[ucont addUserScript:script];
WKWebViewConfiguration *wcon = [WKWebViewConfiguration new];
wcon.userContentController = ucont;
switch (value) {
case NormalWebViewMode:
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];;
break;
case OriginalParserMode:
// self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];;//
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:wcon];
break;
default:
break;
}
//Safariで開くボタンの追加
UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAction
target:self
action:@selector(actionButton)];
self.navigationItem.rightBarButtonItem = doneButton;
// WKWebView インスタンスの生成
// WKWebView インスタンスを画面に配置する
[self.view insertSubview:self.webView atIndex:0];
[self.view bringSubviewToFront:self.webView];
// Auto Layout の設定
self.webView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addConstraints:@[
[NSLayoutConstraint constraintWithItem:self.webView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeWidth
multiplier:1.0
constant:0],
[NSLayoutConstraint constraintWithItem:self.webView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeHeight
multiplier:1.0
constant:0]
]];
//navのtitle設定
[self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
// UIデリゲートにこのビューコントローラを設定する
self.webView.UIDelegate = self;
self.webView.navigationDelegate = self;
self.navigationItem.title = _viewTitle;
//webViewのバウンスをさせない
_webView.scrollView.bounces =NO;
self.tabBarController.tabBar.translucent = NO;
//NSString *html = [_article getHTMLResource];
//このあたりでヘッダと統合の作業が必要
//いってみよー
NSURL *url;
NSURLRequest *req;
NSString *html = [self optimizeWebPage];
NSURL *baseURL = [NSURL URLWithString:_baseURL];
switch (value) {
case OriginalParserMode:
case NormalWebViewMode:
url = [NSURL URLWithString:_articleURL];
req = [NSURLRequest requestWithURL:url];
[_webView loadRequest:req];
break;
/*
case OriginalParserMode:
//いってみよー
[_webView loadHTMLString:html baseURL:baseURL];
break;
*/
default:
break;
}
}
-(void)viewWillAppear:(BOOL)animated{
NSInteger value = _webViewMode;
switch (value) {
case NormalWebViewMode:
break;
case OriginalParserMode:
break;
default:
break;
}
}
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
message:nil
preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"OK"
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action) {
completionHandler();
}]];
[self presentViewController:alertController animated:YES completion:^{}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
NSURL *url = navigationAction.request.URL;
//NSString *urlString = (url) ? url.absoluteString : @"";
//WKFrameInfo *sourceFrame = navigationAction.sourceFrame;
WKFrameInfo *targetFrame = navigationAction.targetFrame;
/*// iTunes: アプリのリンクなど
if ([urlString isMatch:RX(@"\\/\\/itunes\\.apple\\.com\\/")]) {
[[UIApplication sharedApplication] openURL:url];
decisionHandler(WKNavigationActionPolicyCancel);
return;
}
// http(s) 以外のプロトコル: 他のアプリへ移動する場合
else if (![urlString isMatch:[@"^https?:\\/\\/." toRxIgnoreCase:YES]]) {
[[UIApplication sharedApplication] openURL:url];
decisionHandler(WKNavigationActionPolicyCancel);
return;
}*/
switch (navigationAction.navigationType) {
case WKNavigationTypeLinkActivated: {
NSLog(@"WKNavigationTypeLinkActivated::");
// <a href="..." target="_blank"> が押されたとき
if (!targetFrame) {
[webView loadRequest:[NSURLRequest requestWithURL:url]];
}
break;
}
case WKNavigationTypeFormSubmitted: {
NSLog(@"WKNavigationTypeFormSubmitted::");
break;
}
case WKNavigationTypeBackForward: {
NSLog(@"WKNavigationTypeBackForward::");
break;
}
case WKNavigationTypeReload: {
NSLog(@"WKNavigationTypeReload::");
break;
}
case WKNavigationTypeFormResubmitted: {
NSLog(@"WKNavigationTypeFormResubmitted::");
break;
}
case WKNavigationTypeOther: {
NSLog(@"WKNavigationTypeOther::");
break;
}
default: {
break;
}
}
decisionHandler(WKNavigationActionPolicyAllow);
}
- (void)actionButton {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:_articleURL message:nil preferredStyle:UIAlertControllerStyleActionSheet];
// 上から順にボタンを配置
[alertController addAction:[UIAlertAction actionWithTitle:@"Safariで開く" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self selectedActionWith:1];
}]];
[alertController addAction:[UIAlertAction actionWithTitle:@"キャンセル" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self selectedActionWith:0];
}]];
[self presentViewController:alertController animated:YES completion:nil];
}
-(void)selectedActionWith:(int)index{
NSLog(@"選択: %d",index);
switch (index) {
case 0:
break;
case 1:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:_articleURL]];
break;
default:
break;
}
}
/* HTML全体をパースしてページの余分な部分を切り落とします。 */
-(NSString *)optimizeWebPage{
//書き出し用のStringを準備
NSMutableString *tempArticle = [[NSMutableString alloc] init];
NSString *headerHtmlPath = [[NSBundle mainBundle] pathForResource:@"museumInfoCss" ofType:@"dhtml" inDirectory:@"htdocs" ];
[tempArticle appendString:[NSString stringWithContentsOfFile:headerHtmlPath encoding:NSUTF8StringEncoding error:nil]];
[tempArticle appendString:@"<div class=\"btm_content_area\" id=\"btm_content_area\">\n"]; //<div class="btm_content_area" id="btm_content_area">
[tempArticle appendString:@"<div class=\"container\">\n"]; //<div class="container">
/* 指定したIDのページを取得します 将来英語対応するときに必要かも */
/*NSString *articleURL;
switch (language) {
case Japanese:
articleURL = [[NSString alloc] initWithFormat:@"http://www.ncsm.city.nagoya.jp/cgi-bin/visit/exhibition_guide/exhibit.cgi?id=%@",exhibitionId];
break;
case English:
articleURL = [[NSString alloc] initWithFormat:@"http://www.ncsm.city.nagoya.jp/cgi-bin/en/exhibition_guide/exhibit.cgi?id=%@",exhibitionId];
break;
default:
articleURL = [[NSString alloc] initWithFormat:@"http://www.ncsm.city.nagoya.jp/cgi-bin/visit/exhibition_guide/exhibit.cgi?id=%@",exhibitionId];
break;
}*/
NSData *data = [Utils getDataFromURL:_articleURL];
/* パーサに渡して解析を開始 */
NSString *html = [[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding];
NSError *error = nil;
HTMLParser *parser = [[HTMLParser alloc] initWithString:html error:&error];
/* bodyタグの抽出 */
HTMLNode *bodyNode = [parser body];
/* <div id="btm_content_area">タグ内を抽出 */
HTMLNode *contentNode = [bodyNode findChildWithAttribute:@"id" matchingName:@"btm_content_area" allowPartial:true];
/* 本文 */
[tempArticle appendString:@"<div class=\"container\">\n"];
[tempArticle appendString:[contentNode rawContents]];
[tempArticle appendString:@"</div>\n"];
[tempArticle appendString:@"</div>\n"];
[tempArticle appendString:@"</div>\n"];
[tempArticle appendString:@"</div>\n"];
[tempArticle appendString:@"</div>\n"];
[tempArticle appendString:@"</div>\n"];
[tempArticle appendString:@"</div>\n"];
return tempArticle;
//return @"";
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment