UIWebView / NSURLProtocol - 脱机时不可访问的外部资产的占位符

时间:2015-09-17 16:39:11

标签: ios nsurlprotocol

我的应用是用于在iPhone / iPad上查看图书的电子阅读器。用户可以选择将我们在设备上保存的图书下载为.epub文件(压缩内容) - 这样可以在离线状态下查看图书。页面内容以html格式显示。

有些资产(如视频)不在此.epub内容中。当用户导航到这样的页面时,我必须检测不在.ePub中的外部资产,并显示一个简单的占位符,文本“离线时该内容不可用”。

这些视频可以嵌入到iFrame html标记或对象标记中。

现在我们有一个继承自NSURLProtocol抽象类的类,我正在使用它来处理这个需求。我实现了这三种方法:

+ (BOOL) canInitWithRequest:(NSURLRequest *)request

- (void)startLoading

- (void) sendResponse:(NSData *)data mimetype:(NSString *)mimetype url:(NSURL *)url

我现在的问题是我有一个简单的.png显示“此内容在离线时不可用”,但它很难看,因为有时iFrame的区域小于图像。如何缩放它以适应?还是有更好的方法?只要我能够显示内容不可用的消息,它就不必是图像。我在startLoading方法中的当前代码:

- (void) startLoading
{
    …
    NSString *bundlePath = [NSString stringWithFormat:@"%@/%@",[[NSBundle mainBundle] bundlePath],@"PxeReaderResources.bundle"];
    NSString *pathToPlaceholder = [NSString stringWithFormat:@"%@/%@",bundlePath,@"OfflinePlaceholder.png"]; //my placeholder image
    NSLog(@"Path to placeholder is: %@", pathToPlaceholder);

    data = [[NSFileManager defaultManager] contentsAtPath:pathToPlaceholder];

    … 

    [self sendResponse:data mimetype:@"application/octet-stream" url:self.request.URL];
}

- (void) sendResponse:(NSData *)data mimetype:(NSString *)mimetype url:(NSURL *)url
{
    NSDictionary *headers = @{@"Content-Type" : mimetype, @"Access-Control-Allow-Origin" : @"*", @"Cache-control" : @"no-cache"};
    NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:url statusCode:200 HTTPVersion:@"HTTP/1.1" headerFields:headers];

    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    [self.client URLProtocol:self didLoadData:data];
    [self.client URLProtocolDidFinishLoading:self];
}

感谢您提出任何建议。

2 个答案:

答案 0 :(得分:1)

我能够发送一个简单的自定义html div标签来代替外部资产。这是代码 - 希望这会对某人有所帮助。 注意:所有这些代码都在我的自定义类中,它继承自NSURLProtocol

#define EXTERNAL_REQUEST_KEY @"ExternalRequest"

+ (BOOL) canInitWithRequest:(NSURLRequest *)request
{
     NSString* filePath = [[PxePlayer sharedInstance] getBaseURL]; //gets base path to the epub zipped folder

    if ([Reachability isReachable])
    {
        return filePath != nil && [@"file" caseInsensitiveCompare:request.URL.scheme] == NSOrderedSame;
    }
    else
    {
        if ([request.URL.scheme isEqualToString:@"https"] || [request.URL.scheme isEqualToString:@"http"]) //these schemes won't work if offline
        {
            [NSURLProtocol setProperty:@YES forKey:EXTERNAL_REQUEST_KEY inRequest:(NSMutableURLRequest*)request]; //marking those request so that we will only provide placeholder for these requests
        }
        return filePath != nil && ([@"file" caseInsensitiveCompare:request.URL.scheme] == NSOrderedSame ||
                               [@"https" caseInsensitiveCompare:request.URL.scheme] == NSOrderedSame ||
                               [@"http" caseInsensitiveCompare:request.URL.scheme] == NSOrderedSame);
    }
}

- (void) startLoading
{
    ...

    if ([NSURLProtocol propertyForKey:EXTERNAL_REQUEST_KEY inRequest:self.request])
    {   
        custMimeType = @"text/html";

        data = [self prepareDataForPlaceholderForExternalAsset];
    }

    ...

    if (data)
    {
        //Now ready to send the placeholder as custom response
        [self sendResponse:data mimetype:custMimeType url:self.request.URL];
    }
}

//method to create a simple div tag as NSData
- (NSData*) prepareDataForPlaceholderForExternalAsset
{
    NSString *placeholder =
    @"<div style=\"background-color:#efefef; border:1px solid #999999; text-align:center; width:100%; height:100%\"> \
        <font font-family=\"Helvetica Neue\" font-weight=\"Medium\" size=\"5\" color=\"#b3b3b3\"> \
          <div style=\"display:inline-block; margin-top:5%\"> \
            This content is unavailable when offline or printing \
          </div> \
        </font> \
      </div>";

    return [placeholder dataUsingEncoding:NSUTF8StringEncoding];
}

- (void) sendResponse:(NSData *)data mimetype:(NSString *)mimetype url:(NSURL *)url
{
    NSDictionary *headers = @{@"Content-Type" : mimetype, @"Access-Control-Allow-Origin" : @"*", @"Cache-control" : @"no-cache"};
    NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:url statusCode:200 HTTPVersion:@"HTTP/1.1" headerFields:headers];

    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    [self.client URLProtocol:self didLoadData:data];
    [self.client URLProtocolDidFinishLoading:self];
}

答案 1 :(得分:0)

您可以使用(注入)JavaScript来遍历DOM,寻找这些对象/ iframe标记,并将其替换为漂亮的“Not available offline”消息,而不是尝试拦截资源负载。您可能会在加载页面后执行此操作,或者您可以尝试在将HTML传递到WebView之前解析和修改HTML。