html文件如何加载iOS本地图片

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/sinat_30162391/article/details/74982555

这是我在stackOverflow看到的解决办法, 提供给有需要的同学, 不过模拟器测试, 加载效果很差. 感兴趣可以看看, 后面有demo链接.

@interface MyCustomURLProtocol : NSURLProtocol
{
    NSURLRequest *request;
}
+ (BOOL)canInitWithRequest:(NSURLRequest *)theRequest;
@end
@implementation MyCustomURLProtocol

+ (BOOL)canInitWithRequest:(NSURLRequest *)theRequest
{
    if ([theRequest.URL.scheme caseInsensitiveCompare:@"myapp"] == NSOrderedSame) {
        return YES;
    }
    return NO;
}

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

- (void)startLoading
{
    NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[request URL]
                                                        MIMEType:@"image/png"
                                           expectedContentLength:-1
                                                textEncodingName:nil];

    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"image1" ofType:@"png"];
    NSData *data = [NSData dataWithContentsOfFile:imagePath];

    [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    [[self client] URLProtocol:self didLoadData:data];
    [[self client] URLProtocolDidFinishLoading:self];
    NSLog(@"start loading !");

}

- (void)stopLoading
{
    NSLog(@"something went wrong!");
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 375, 667)];
    [self.view addSubview:self.webView];
    [NSURLProtocol registerClass:[MyCustomURLProtocol class]];
    NSString *localHtmlFilePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"html"];
    NSString *localHtmlFileURL = [NSString stringWithFormat:@"file://%@", localHtmlFilePath];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:localHtmlFileURL]]];
    NSString *html = [NSString stringWithContentsOfFile:localHtmlFilePath encoding:NSUTF8StringEncoding error:nil];
    [webView loadHTMLString:html baseURL:nil];
}

.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <h1>we are loading a custom protocol</h1>
    <b>image?</b><br/>
    <img src="myapp://image1.png" />
</head>
<body>

</body>
</html>

https://github.com/summerxx27/htmlLoadiOSImage

猜你喜欢

转载自blog.csdn.net/sinat_30162391/article/details/74982555