read local html file and show on webview - objective-c

I have been able to read a file called 'exerciseA.htm' from a live url. but now i need to bring the file locally add it to the project and read it from there. I have dragged the file into xcode to add it. Now i need to read its contents to a string, however the following doesnt seem to work:
NSString* exerciseAPage = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"exerciseA" ofType:#"htm"] encoding:NSUTF8StringEncoding error:&error];
[exerciseWebViewA loadHTMLString:exerciseAPage baseURL:nil];
Is this the correct way to load local htm file to a webview?

I do it the following way (Which is basically the same as you specify):
NSURL *url = [[NSBundle mainBundle] URLForResource:nameOfHtmlFile withExtension:#"html"];
NSError *error;
NSString *contentString = [NSString stringWithContentsOfURL:url encoding:NSStringEncodingConversionAllowLossy error:&error];
NSURL *baseUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[self.webView loadHTMLString:contentString baseURL:baseUrl];
Hope this helps
Alex

Related

Images in my html file in UIWebView not showing

Here is my scenario:
I have a folder called "HTML" in my bundle. This folder has an HTML file and 5 images. The HTML file references all the images at some point using a simple img tag.
<img src="tut_navigation.png" />
Now I have a UIWebview which I used to load the HTML file. All of the contents of the HTML file are rendered correctly except for my images. My images are not showing up for some strange reason. Then I did some research and found related posts saying to load URL like so:
NSString *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"tutorial" ofType:#"html" inDirectory:#"HTML"]];
NSString* htmlString = [NSString stringWithContentsOfFile:url encoding:NSUTF8StringEncoding error:nil];
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[self.webView loadHTMLString:htmlString baseURL:baseURL];
Once I made this change and ran it again, this time only the first image is loading up, the others ones are not. I'm lost as to what the issue is. When I view this HTML file in a web browser, everything is working fine. Any ideas?
The baseURL needs to be the a path to the HTML folder inside the app bundle, not (as you have it) a path to the app bundle itself.
Change this:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[self.webView loadHTMLString:htmlString baseURL:baseURL];
To this:
[self.webView loadHTMLString:htmlString baseURL:url];
You had the right URL for the base URL (url) and then you just threw it away and substituted the URL of the bundle itself, which is wrong.
Even better, forget the base URL and just use a URL instead of a path string for the file itself:
NSString *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"tutorial" ofType:#"html" inDirectory:#"HTML"]];
NSURLRequest* req = [[NSURLRequest alloc] initWithURL:url];
[self.webview loadRequest: req];

Using AFNetworking to download a pdf from the web in appdelegate and then trying to load that stored pdf in a UIWebview on another page

I am using AFNetworking to download a pdf (that will change on a weekly basis) and save it into the documents directory with this code:
//Get the PDF
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.somewebsiteaddress/CurrentEdition1.pdf"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"CurrentEdition1.pdf"];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Successfully downloaded file to %#", filePath);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[operation start];
I then want to read that saved file in another section of the app in a UIWebView (after it has downloaded) and use this code:
//Now create Request for the file that was saved in your documents folder
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:#"CurrentEdition1.pdf"];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webVieweedition setUserInteractionEnabled:YES];
[webVieweedition setDelegate:self];
[webVieweedition loadRequest:requestObj];
I have used a few single page pdf documents to test with - loading them up on the server and then seeing if they are downloaded and then viewed when changed. Problem is, this seems to only be working about 50% of the time. I'll put a new file up and sometimes the correct one will be shown in the UIWebView and sometimes it will show the previous one and not the new one. I am waiting until I see the download completed message before I try to go to the UIWebView (although I know clients won't do that, but that's a whole other question). Anyway, I'm new to XCode and have just been a web html guy. This has had my head spinning for two days. Using Storyboards, ARC, XCode 4.6.2.
If i understood right, sometimes you see the same pdfs in app, although you changed them on webserver?May be the reason is cache, try construct request this way, ignoring caching
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.somewebsiteaddress/CurrentEdition1.pdf"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];

Images & CSS not loading in iPhone UIWebView

When my UIWebView loads my index.html the CSS and JavaScript references show as broken. What is wrong with the code below? (I verified that appUrlString is pointing to the correct directory)
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:#"index" ofType:#"html" inDirectory:#""];
NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
NSString *appUrlString = [NSString stringWithFormat:#"%#/web/", [[NSBundle mainBundle] resourcePath]];
NSURL *appUrl = [NSURL URLWithString:appUrlString];
[_appWebView loadData:htmlData MIMEType:#"text/html" textEncodingName:#"UTF-8" baseURL:appUrl];
This is what shows in the simulator.
You should use
NSURL *appUrl = [NSURL fileURLWithPath:appUrlString];
because it's a local filePath. In your version 'appURL' was giving back nil.
So no baseurl got set.

How to store a pdf file loaded into an UIWebView in my Documents directory?

Currently, I detect if the UIWebView load a pdf file by doing a check on the current URL. Next I download the pdf file with ASIHTTPRequest library. The problem is that if the file is display in the UIWebView, is that it is already downloaded somewhere, so I download this file twice. How can I get this file load in my UIWebView ?
The purpose is to store this file loaded in my UIWebView in my Document directory.
Here's how you can download, read and store your pdf locally in iphone application, so that you don't have to download regularly:
First create UIWebView and include <<UIWebViewDelegate>>
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"YourPDF.pdf"];
if(![[NSFileManager defaultManager] fileExistsAtPath:filePath]){ // if file not present
// download file , here "https://s3.amazonaws.com/hgjgj.pdf" = pdf downloading link
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"https://s3.amazonaws.com/hgjgj.pdf"]];
//Store the downloaded file in documents directory as a NSData format
[pdfData writeToFile:filePath atomically:YES];
}
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[yourWebView setUserInteractionEnabled:YES];
[yourWebView setDelegate:self];
yourWebView.scalesPageToFit = YES;
[yourWebView loadRequest:requestObj];
Or, if you simply want to read/load pdf from your Resource folder then simply do this :
NSString* filePath= [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"pdf"]];
/// or you can even read docs file as : pathForResource:#"sample" ofType:#"docx"]
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[yourWebView setUserInteractionEnabled:YES];
[yourWebView setDelegate:self];
yourWebView.scalesPageToFit = YES;
[yourWebView loadRequest:requestObj];
All I can suggest is either to download it a second time, or put it in the temporal storage and then put it it the UIWebView and when the user asks, then put it where you want from the temporal storage.

playing sound files in resources folder

I have some mp3 files in my resources folder, how can i play those mp3 files? I just know their name.
Just to supplement #Georg's answer.
As you can see from the doc, -URLForResource:withExtension: is available only since 4.0. As 3.x is still widespread, it's better to use the backward-compatible methods:
By converting a path to NSURL:
NSString* path = [[NSBundle mainBundle] pathForResource:#"myFile" ofType:#"mp3"];
NSURL* url = [NSURL fileURLWithPath:path];
....
or, by CoreFoundation methods:
CFURLRef url = CFBundleCopyResourceURL(CFBundleGetMain(),
CFSTR("myFile"), CFSTR("mp3"), NULL);
....
CFRelease(url);
You can use the AVAudioPlayer. To get the URL for the files use NSBundles -URLForResource:withExtension: (or downward compatible alternatives, see Kennys answer):
NSURL *url = [[NSBundle mainBundle] URLForResource:#"myFile" withExtension:#"mp3"];
NSError *error = 0;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
// check error ...
[player play];
// ...
And don't forget to read the Multimedia Programming Guides section on using audio.