Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

html - How to read image file at documents directory from ios webview

I am downloading image file and write to documents directory like below:

NSArray   *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString  *documentsDirectory = [paths objectAtIndex:0];

NSString  *objURL = @"http://test.test.com/file/image.png";
NSURL     *objurl = [NSURL URLWithString:objURL];
NSData    *imgData = [NSData dataWithContentsOfURL:objurl];

NSString *imgFile = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"image.png"];
[imgData writeToFile:imgFile atomically:YES];

In my webView, I loaded a html file from my bundle resource to use in my webView, but how do I have the tag in html to read the image.png in documents directory?

<html>
<body>
    <img src="../what/is/the/path/to/use/image.png" />
</body>
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could give the URL for this image using an absolute path with a file:// scheme:

NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)[0];
NSString *filePath = [NSString stringWithFormat:@"file://%@/image.png", documentsDirectory];

You could then run some javascript to update the src tag to update it to the new path:

NSString *javascript = [NSString stringWithFormat:@"var imageElement = document.getElementById('localFile'); imageElement.setAttribute('src', '%@');", filePath];
[self.webView stringByEvaluatingJavaScriptFromString:javascript];

In your HTML the path would look like something like:

<html>
    <body>
        <img id="localFile" src="file:///var/mobile/Applications/3D7D43E8-FA5E-4B19-B74C-669F7D1F3093/Documents/image.png" />
    </body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...