UIWebView's baseURL set to NSDocumentDirectory? - iphone

Is it possible to set the baseURL of a UIWebView to NSDocumentDirectory? If yes, how does one do that?
What I'm trying to do is to display some downloaded images locally in the /img src=""/ tag.
Thanks in advance for any suggestions.

You could try to do what this person did: UIWebView: Absolute path for images in app documents folder
Basically, it uses the document directory path for the image source, and not simply img src="image_name"

To load your local file inside webview do the following
NSString *imagePath = [[NSBundle mainBundle] resourcePath];
imagePath = [imagePath stringByReplacingOccurrencesOfString:#"/" withString:#"//"];
imagePath = [imagePath stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *HTMLData = #"
<img src="YOUR_IMAGE.jpg" alt="" width="100" height="100" />";
[webView loadHTMLString:HTMLData baseURL:[NSURL URLWithString: [NSString stringWithFormat:#"file:/%#//",imagePath]]];
This should load YOUR_IMAGE.jpg inside the UIWebView
read more from
http://dblog.com.au/iphone-development/loading-local-files-into-uiwebview/

Related

Display UIImage from camera in UIWebView

In my iPhone app, I want the user to be able to take a picture with the camera, then have that image appear in amongst some locally stored HTML in a UIWebView.
So I've got the UIImage object from the UIImagePickerController, now I need to find out how to save it to memory so I can reference it in the UIWebView.
Note that I don't just want the image on it's own in the UIWebView (I want to use the picture as a background-image in some HTML with other images layered on top). I'm also using other images and HTML that are stored in the app, that I'm referencing by setting the baseURL of the UIWebView to the bundle path, like:
NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[self.webView loadHTMLString:html baseURL:baseURL];
You definitely have the option of saving the file locally, getting it's absolute path and using that.
Another option I used for a hybrid app once is converting the UIImage to Base64 string and pass that through javascript to the webview to do whatever you want it to do.
To do that that after getting the UIImage encode it (there are various libraries out there to do this:
UIImage *image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSString *base64EncodedImage = [Base64 encode:UIImageJPEGRepresentation(image, 0.5)];
Then in your HTML you could have method that is given the base64 images and sets it to some IMG or background or whatever you need:
function cameraCallback(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
Or
<img src="data:image/gif;base64, [YOUR BASE64 STRING HERE]" alt="" width="80" height="15" />
Then in the HTML in the webview you would use
[mywebview stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:#"cameraCallback(%#)", base64EncodedImage]];
This is the way I ended up doing this. In the code that handles the image taken using the camera I actually save the file directly to disc:
// Get the image out of the camera
UIImage *image = (UIImage *)[info valueForKey:UIImagePickerControllerOriginalImage];
// Images from the camera are always in landscape, so rotate
UIImage *rotatedImage = scaleAndRotateImage(self.image);
// Save the image to the filesystem
NSData *imageData = UIImagePNGRepresentation(rotatedImage);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString* savePath = [documentsPath stringByAppendingPathComponent:#"CameraPhoto.png"];
BOOL result = [imageData writeToFile:savePath atomically:YES];
The function to rotate the image is copied straight from this blog, http://blog.logichigh.com/2008/06/05/uiimage-fix/.
Then when I want to display this image within the UIWebView, I just do a string replace to reference inject the path to the image. So in my HTML there's like <img src="{CameraPhotoUrl}" /> and then:
// Build the reference to the image we just saved
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *cameraImagePath = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"CameraPhoto.png?x=%#", [[NSDate date] description]]];
// Load the HTML into the webview
NSString *htmlFilePath = [[NSBundle mainBundle] pathForResource:#"MyHtmlFile" ofType:#"htm"];
NSString *html = [NSString stringWithContentsOfFile:htmlFilePath encoding:NSUTF8StringEncoding error:nil];
html = [html stringByReplacingOccurrencesOfString:#"{CameraPhotoUrl}" withString:cameraImagePath];
NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[self.webView loadHTMLString:html baseURL:baseURL];
Voila! Note that I'm appending a date-based query string parameter to the CameraPhoto.png filename simply to prevent caching.

Question about embedding a UIImage in a UIWebview; how do you get rid of the border?

Here is the code I am using:
NSString *imagePath = [[NSBundle mainBundle] resourcePath];
imagePath = [imagePath stringByReplacingOccurrencesOfString:#"/" withString:#"//"];
imagePath = [imagePath stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *HTMLData = #"<meta name=\"viewport\" content=\"width=320\"/> <img src=\"image.png\" alt=\"\" width=\"320\" height=\"480\">";
[self.webView loadHTMLString:HTMLData baseURL:[NSURL URLWithString: [NSString stringWithFormat:#"file:/%#//",imagePath]]];
[self.webView setScalesPageToFit:YES];
There is a white border surrounding the image in the web view. Is there any way to just have the image take up the screen?
Edit: Added screenshot
Thanks in advance for your help.
Try adding a body tag that has its CSS margin property set to 0px. The generated HTML should look like this:
<meta name="viewport" content="width=320"/>
<body style="margin:0px;">
...img tag goes here...
</body>
Have your tried adding border="0"
Change: <img src=\"image.png\" alt=\"\" width=\"320\" height=\"480\">
To: <img src=\"image.png\" alt=\"\" width=\"320\" height=\"480\ border=\"0\">

Loading webpage into UIwebview but images from local

I have web page having 1000's of images and values. Whenever I load the page to UIWebView it gets loaded with values but as there are so many images it takes time to download.
So is there any way, I can download the page from web but images from local.
Any help is really appreciated.
Thank you,
Ankita
If you have your HTML from webserver and images at local
yourBaseURL = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[webView loadHTMLString:#"YourHTML" baseURL:yourBaseURL]
and your HTML contains name of local image stored like
Image Tag like --> imgage src='fig1.jpg width=150 height=150 align="left"
Than this should work.
Not exactly as you required though this way you can load local images in webView.
Basically:
Download HTML from server.
NSURL *URL = [[NSURL alloc] initWithString:#"http://www.example.com/page.php"];
NSError *error = nil;
NSStringEncoding encoding;
NSString *theSource = [[NSString alloc] initWithContentsOfURL:URL usedEncoding:&encoding error:&error];
Replace the file references to load images locally.
Note the double slashes, this seems important.
// Replace:
<img src="File.png">
// By something like:
<img src="file://Path//To//Resources//File.png">
Detailed information how to do this (check post by Joe D'Andrea):
Link to resources inside WebView - iPhone
Finally make the UIWebView load the HTML:
[webView loadHTMLString:htmlString baseURL:baseURL];
Now it should load the 'fresh' HTML from the server with local images.
This works quite well for me.
NSURL *myBaseURL = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] bundlePath]];
NSString *myString = [[managedObject valueForKey:#"long_presentation"] stringByReplacingOccurrencesOfString:#"/FooFolder/BarFolder" withString:[NSString stringWithFormat:#"%#/FooFolder/BarFolder", [[NSBundle mainBundle] bundlePath] ] ];
[attractionWebView loadHTMLString:myString baseURL:myBaseURL];
I had to include a replacement for the image source
img src="FooFolder/BarFolder/my_image.jpg" ...
to get the right path.

Correct way to load image into UIWebView from NSData object

I have downloaded a gif image into an NSData object (I've checked the contents of the NSData object and it's definitely populated). Now I want to load that image into my UIWebView. I've tried the following:
[webView loadData:imageData MIMEType:#"image/gif" textEncodingName:nil baseURL:nil];
but I get a blank UIWebView. Loading the image from the same URL directly works fine:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl]];
[imageView loadRequest:request];
Do I need to set the textEncodingName to something, or am I doing something else wrong?
I want to load the image manually so I can report progress to the user, but it's an animated gif, so when it's done I want to show it in a UIWebView.
Edit: Perhaps I need to wrap my image in HTML somehow? Is there a way to do this without having to save it to disk?
I tested the code with PNG ("image/png"), JPG ("image/jpeg") and GIF ("image/gif"), and it works as expected:
[webView loadData:imageData MIMEType:imageMIMEType textEncodingName:nil baseURL:nil];
Now, what's wrong with your app?
the imageData is not a well-formed image data. Try opening the file with a web browser or an image editor to check it.
the MIME type is incorrect. Look at the first bytes of the data to determine the actual file type.
webView is not connected in IB, is nil, is hidden, is covered with another view, is off screen, has a CGRectZero frame, etc.
I did not really try to load image to UIWebView but a google search gives me. I think your image string must have a good path and looks like a URL
NSString *imagePath = [[NSBundle mainBundle] resourcePath];
imagePath = [imagePath stringByReplacingOccurrencesOfString:#"/" withString:#"//"];
imagePath = [imagePath stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *HTMLData = #"
<h1>Hello this is a test</h1>
<img src="sample.jpg" alt="" width="100" height="100" />";
[webView loadHTMLString:HTMLData baseURL:[NSURL URLWithString: [NSString stringWithFormat:#"file:/%#//",imagePath]]];
You can see more details here : Loading local files to UIWebView
UIImage *screenshot= [UIImage imageAtPath:
[[NSBundle mainBundle] pathForResource:#"MfLogo_aboutus" ofType:#"png"]];
NSData *myData = UIImagePNGRepresentation(screenshot);
[vc addAttachmentData:myData mimeType:#"image/png" fileName:#"logo.png"];
You can load urlImage into webview which is not saved locally as shown below code
NSString *str = #"";
str = [str stringByAppendingString:#"http://t3.gstatic.com/images?q=tbn:7agzdcFyZ715EM:http://files.walerian.info/Funny/Animals/funny-pictures-firefox-file-transfer-is-complete.jpg"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
[webView loadData:data MIMEType:#"application/jpg" textEncodingName:#"UTF-8" baseURL:[NSURL URLWithString:#"http://google.com"]];
I had the same problem and I found somewhere else that you have to provide a value in the baseURL parameter. I also had encoding set:
textEncodingName:#"UTF-8" baseURL:[NSURL URLWithString:#"http://localhost/"]];
When I had nil in the baseURL parameter it would not load. By putting something that's basically irrelevant in there the MS docs all worked.
You may want to try assigning a delegate to the webview and implementing the method:
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
To see more specifically what error you're getting. If it doesn't get called, implement the method:
- (void)webViewDidFinishLoad:(UIWebView *)webView
as well, just to make sure something is happening, otherwise there might be an issue with UIWebView (assuming you haven't returned NO from webView:shouldStartLoadWithRequest:navigationType:)
To expand on Ed Marty's comment:
The HTML command to put in a base 64 image is:
<img src="data:image/png;base64,##PUT THE BASE64 DATA HERE###" />
I have a category (I'm not sure where it came from, not me...) available on my website that converts NSData to it's Base64 string representation.
Header
Implementation
Easy enough to do, assuming 'imageData' is the NSData variable containing your image:
[imageData base64Encoding] into the above string.
try this code
// 1) Get: Get string from “outline.plist” in the “DrillDownSave”-codesample.
savedUrlString = [item objectForKey: #"itemUrl"];
// 2) Set: The url in string-format, excluding the html-appendix.
NSString *tempUrlString = savedUrlString;
// 3) Set: Format a url-string correctly. The html-file is located locally.
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:tempUrlString ofType:#”html”];
// 4) Set: Set an “NSData”-object of the url-sting.
NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
// 5. Gets the path to the main bundle root folder
NSString *imagePath = [[NSBundle mainBundle] resourcePath];
// 6. Need to be double-slashes to work correctly with UIWebView, so change all “/” to “//”
imagePath = [imagePath stringByReplacingOccurrencesOfString:#"/" withString:#"//"];
// 7. Also need to replace all spaces with “%20″
imagePath = [imagePath stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
// Load: Loads the local html-page.
[webView loadData:htmlData MIMEType:#"text/html" textEncodingName:#"UTF-8" baseURL:[NSURL URLWithString:[NSString stringWithFormat:#"file:/%#//",imagePath]]];
Here's an alternative method:
Save the image you downloaded into your documents folder.
Then get that image's url. Then write a simple html file
using that image url in the IMG SRC tag.
NSLog(#"url=%#", fileURL); // fileURL is the image url in doc folder of your app
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/toOpen.html",
documentsDirectory];
//create simple html file and format the url into the IMG SRC tag
NSString *content = [NSString stringWithFormat:#"<html><body><img src=%#></body></html>",fileURL];
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil]; // now we have a HTML file in our doc
// open the HTML file we wrote in the webview
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"life.html"];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[yourWebView loadRequest:request];
NSString *pathForFile = [[NSBundle mainBundle] pathForResource: #"fireballscopy" ofType: #"gif"];
NSData *dataOfGif = [NSData dataWithContentsOfFile: pathForFile];
[Web_View loadData:dataOfGif MIMEType:#"image/gif" textEncodingName:nil baseURL:nil];

iPhone Dev: UIWebView baseUrl to resources in Documents folder not App bundle

Greetings! Can anyone please kindly assist me finding a way around the following:
load an html into a UIWebView using loadHTMLString and include(using baseURL) the resources such as the CSS, image files from folders within user's Documents directory - and not from the MainBundle of the application.
I have seen tutorials on how to use baseURL to load within the application bundle/MainBundle which is straightforward but not with resources from the iPhone's Documents directories.
The structure of my documents folder is as follows:
dirX
|---> file.xml
|---> dirCSS
|---> style.css
I can retrieve the full path to the dir X(Users/......./dir X). However, when passing that path to the UIWebView's baseURL such that
[webView loadHTMLString:fileXMLString baseURL:pathToDirX]
... webView does not recognize the resources(eg style.css within dirCSS) as href'ed within the fileXMLString
<link href="dirCSS/style.css" rel="stylesheet" />
So currently my application can successfully load the html string but does not load the stylesheet as the link to the CSS within the html string are relative - eg. css/style.css
Any help is very much appreciated :)
After some googling I have finally found a fitting solution for the question I posed. Hopefully this would help those who face the same problem.
The trick is with the formatting of the string path when creating an NSURL object for baseURL of a UIWebView. Although usually I use the typical "Users/...../dir/file" in most cases, loading using UIWebView's loadHTMLString:baseURL needs a different approach.
As described in http://dblog.com.au/iphone-development/loading-local-files-into-uiwebview/, where I got the solution, string path to the resources just needs to have slashes to be replaced with double-slashes and spaces with %20:
NSString *imagePath = [[NSBundle mainBundle] resourcePath];
imagePath = [imagePath stringByReplacingOccurrencesOfString:#"/" withString:#"//"];
imagePath = [imagePath stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *HTMLData = #"
<h1>Hello this is a test</h1>
<img src="sample.jpg" alt="" width="100" height="100" />";
[webView loadHTMLString:HTMLData baseURL:
[NSURL URLWithString:
[NSString stringWithFormat:#"file:/%#//",imagePath]
]];
Do take note of the replacing of the strings and also the:
[NSString stringWithFormat:#"file:/%#//",imagePath]
Although the example code above is retrieving the path to the mainBundle of the application, it can also work in other folders, ie Documents(and its subfolders) as I did in mine.
Kind regards,
oonoo
PS Thanks again Nic for the reply :)
To get the path to the document directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"index.xml"];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]]
The easiest way to have everything working, is to simply load your index.html from the document directory instead of loading a string. Otherwise set the baseUrl to the document directory.
// call this method and set the directory , Currently it is cache directory . If you want document directory then change NSCacheDirectory to NSDocumentDirectory
-(NSString*)getBasePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
NSUserDomainMask, YES);
NSMutableString *cacheDirectory = [NSMutableString stringWithString:[paths objectAtIndex:0]];
[cacheDirectory appendString:#"/"];
NSRange renge= NSMakeRange(0, cacheDirectory.length);
[cacheDirectory replaceOccurrencesOfString:#"/" withString:#"//" options:NSCaseInsensitiveSearch range:renge];
renge= NSMakeRange(0, cacheDirectory.length);
[cacheDirectory replaceOccurrencesOfString:#" " withString:#"%20" options:NSCaseInsensitiveSearch range:renge];
[cacheDirectory insertString:#"file://" atIndex:0];
//file:////Users//hb//Library//Application%20Support//iPhone%20Simulator//6.0//Applications//3A141D33-390A-4DD2-8825-7DDC07D29894//Library//Caches//
return cacheDirectory;
}