13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

iOSアプリ中のUIWebviewで広告ブロック(Objective-C)

Posted at

背景

UIWebViewにおけるAdBlockをSwiftで実現している記事があるのですが
Objective-C向けのプロジェクトで同じことをしたかったので書きなおして利用させていただきました。
(iOS7, 8で動作確認)

ソースコード

FilteredURLProtocol

FilteredURLProtocol.h
@interface FilteredURLProtocol : NSURLProtocol
+(BOOL)canInitWithRequest:(NSURLRequest *)request;
+(NSURLRequest *)canonicalRequestForRequest:( NSURLRequest *)request;
-(void)startLoading;
-(void)stopLoading;
@end
FilteredURLProtocol.m
# import "FilteredURLProtocol.h"

@implementation FilteredURLProtocol
+(BOOL)canInitWithRequest:(NSURLRequest *)request
{
    NSString *host = request.URL.host;
    if ([host rangeOfString:@"ad"].length) return YES; // <- ここの条件でコンテンツを出し分ける
    return NO;
}

+(NSURLRequest *)canonicalRequestForRequest:( NSURLRequest *)request
{
    return request;
}

-(void)startLoading
{
    NSURLResponse *response = [[NSURLResponse alloc] initWithURL:self.request.URL MIMEType:nil expectedContentLength:0 textEncodingName:nil];
    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    [self.client URLProtocol:self didLoadData:[NSData dataWithBytes:nil length:0]];
    [self.client URLProtocolDidFinishLoading:self];
}

-(void)stopLoading
{}

@end

UIViewControllerでの利用方法

利用したいUIViewControllerでNSURLProtocolに設定してやる。
viewWillAppearとかviewDidLoadあたりに記述してやればOK。
ただし、一度設定すると、アプリ内の全ての場所で適用されてしまう。
そのため、他の画面でこの機能が不要になる場合はviewWillDisappearあたりで解除する。

WebViewController.m
# import "FilteredURLProtocol.h"

// (略)

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [NSURLProtocol registerClass:FilteredURLProtocol.class];    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [NSURLProtocol unregisterClass:FilteredURLProtocol.class];    
    [super viewWillDisappear:animated];
}

参考

iOS - SwiftでNSURLProtocolを使ってUIWebViewの広告をブロックする - Qiita
http://qiita.com/shzero5/items/755fd80bc759a5460c43

iOS Advent Calendar 2011 5日目 / NSURLProtocolの使い方 : As Sloth As Possible
http://faultier.blog.jp/archives/1762587.html

13
12
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
13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?