loading links in in-app browser in a web view in iphone - iphone

I have some local html files in resources.on launch one html,say a.html, is loaded in webview. there are some hyperlinks in that webview(or say the html content) which are links to other html files in my resources.now on click of those links I want to open them in in-app browser.
how to do this.
Any idea????
thnx!!!!

I've not tried this, but it might work!
Create your UIWebView and load the first html file from your bundle
NSString *file = [[NSBundle mainBundle] pathForResource:#"a" ofType:#"html"];
NSString *html = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];
[webView loadHTMLString:[NSString stringWithFormat:#"<html><head></head><body>%#</body></html>", html] baseURL:baseURL];
webView.delegate = self;
Then get when the user taps a link
-(BOOL)webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
if (inType == UIWebViewNavigationTypeLinkClicked) {
// Find which link is selected, get the file and load it into the UIWebView
}
return YES;
}

Related

PDF opening event in IOS app for rendered URL on UIWebView

I am using a UIWebView control and opening a web page URL on it in landscape mode only. In this URL on a particular event a PDF is getting opened. This time the PDF is not getting opened properly (it always shows only first page of the PDF file), and in the Output window i am getting "flatedecode decoding error".
Is there any way so that my application can catch that PDF opening event, and I can open the PDf in Safari or some other browser rather than UIWebView?
Or is there any way in Phonegap to achieve this?
I guess you only need a way to find out whether the specific link opening the PDF is clicked or not?
Make sure you make your viewcontroller a delegate for the webview. Then implement this method
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
navigationType will be UIWebViewNavigationTypeLinkClicked when a new page loads on link click.
request will tell you the URL being opened and you can listen if the URL is one of your PDF. If it is then you can handle it in the method however you want to - download it and open in another web view or open in safari.
More details here.
You can save PDF in your document directory by using this code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [paths objectAtIndex:0];
BOOL isDir = NO;
NSError *error;
//You must check if this directory exist every time
if (! [[NSFileManager defaultManager] fileExistsAtPath:cachePath isDirectory:&isDir] && isDir == NO)
{
[[NSFileManager defaultManager] createDirectoryAtPath:cachePath withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *filePath = [cachePath stringByAppendingPathComponent:#"QRScanner.pdf"];
//webView.request.URL contains current URL of UIWebView, don't forget to set outlet for it
NSData *pdfFile = [NSData dataWithContentsOfURL:webView.request.URL];
if(pdfFile)
{
[AppDelegate obj_appDelegate].Alertview.hidden = YES;
[[AppDelegate obj_appDelegate].activity stopAnimating];
}
[pdfFile writeToFile:filePath atomically:YES];

Showing html file using UIWebView

I have created a UIWebView and used a HTML file to display some contents. But when I run it instead of showing the contents only the whole HTML file coding is coming in the WebView. Please help and tell me what is wrong.
UIWebView *ingradients= [[UIWebView alloc]init];
[ingradients setFrame:CGRectMake(10, 170, 300, 300)];
[ingradients loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"htmlfile" ofType:#"html"]isDirectory:NO]]];
ingradients.delegate=self;
[self.view addSubview:ingradients];
My htmlfile.html contains
<html>
<body>
<p><strong>Ingredients</strong></p>
</body>
</html>
Instead of showing "Ingredients" in bold its showing the whole coding of htmlfile.html
In Your code you alway contain HTML code because your request always return file htmlfile with extantion .html
If you want to get specific value from HTML content you need to Parce HTML content by using Hpple. Also This is documentation with exmple that are use for parse HTML content.
In your case you use: (by using Hpple)
TFHpple *dataParser = [TFHpple hppleWithHTMLData:placesData];
// name of place
NSString *XpathQueryString = #"//p/strong";
NSArray *listOfdata= [dataParser searchWithXPathQuery: XpathQueryString];
That's weird, I have similar code for this and html is rendered as rich text but not as plain text (like you have), the only difference I have is using fileURLWithPath: but not fileURLWithPath:isDirectory:. Here's my code:
NSString *localFilePath = [[NSBundle mainBundle] pathForResource:#"about" ofType:#"html"];
NSURLRequest *localRequest = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:localFilePath]];
[_aboutWebView loadRequest:localRequest];
Maybe you have some issues with file encoding, but as far as I guess, that should not be the case.
Try this code:
- (NSString *) rootPath{
return [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) lastObject];
}
- (NSString *) pathFoResourse : (NSString *) resourseName ofType: (NSString *)type{
NSString *path = [[MMSupport rootPath] stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", resourseName, type]];
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
path = [[NSBundle mainBundle] pathForResource:resourseName ofType:type];
}
NSLog(#"**path:%#**", path);
return path;
}
- (void) loadDataToWebView : (CGRect) frame{
NSString *htmlString = [NSstring stringWithContentsOfFile:[MMSupport pathFoResourse:#"filename" ofType:#"html"] encoding:NSUTF8StringEncoding) error:nil];
UIWebView *webView = [[UIWebView alloc] initWithFrame:frame];
[webView loadHTMLString:htmlString baseURL:nil];
}

Best way to have article text with links on iPhone?

I am making an iPhone app that has a bunch of "articles" with certain words that I want to link to other "articles". I need to display the articles in UITableViewCells.
If there is a way to do this without a web view, that's great.
If I need to use a web view, should I just make <a href> style links? How can I have it jump to the article without creating a bunch of actual html pages, just have it let my program know that they clicked on that link and then the program goes and finds the appropriate article from a plist or something?
I've create a test demo using UIWebView and it works fine.
Create two HTML files:home.html and first.html.
// home.html
Home page. first
// first.html
First page. home
//viewDidLoad
self.webView.delegate = self;
NSString *htmlFilePathString = [[NSBundle mainBundle] pathForResource:#"home" ofType:#"html"];
NSURL *htmlFileURL = [[NSURL alloc] initFileURLWithPath:htmlFilePathString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:htmlFileURL];
[self.webView loadRequest:request];
// webView's delegate:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
return YES;
}

What does loadHTMLString:baseURL:

I new to iOS programming and tried to figure out what loadHTMLString:baseURL: really does, but I can't find a satisfying explanation. The site of Apple just says:
Sets the main page content and base URL.
Can someone please explain this in a more detailed way to me?
I am pretty certain that the baseURL is used just like in regular web pages to properly load ressources that are referenced using relative links. Now the question is, how to set that base URL to a particular folder in the app directory.
This is how mainly content is loaded in a webView. either from a local html file or through a url.
//this is to load local html file. Read the file & give the file contents to webview.
[webView loadHTMLString:someHTMLstring baseURL:[NSURL URLWithString:#""]];
//if webview loads content through a url then
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://google.com"]]]
- (void) loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
is used to load local HTML file, parameter string means content of html file, if your HTML file contains some href tag with relative path, you should set the parameter baseUrl with the base address of the HTML file, or set it nil.
NSString *cachePath = [self cachePath];
NSString *indexHTMLPath = [NSString stringWithFormat:#"%#/index.html", cachePath];
if ([self fileIsExsit:indexHTMLPath]) {
NSString *htmlCont = [NSString stringWithContentsOfFile:indexHTMLPath
encoding:NSUTF8StringEncoding
error:nil];
NSURL *baseURL = [NSURL fileURLWithPath:cachePath];
[self.webView loadHTMLString:htmlCont baseURL:baseURL];
}
- (NSString *)cachePath
{
NSArray* cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
return [cachePath[0] stringByAppendingPathComponent:#"movie"];
}

Displaying ppt, doc, and xls in UIWebView doesn't work but pdf does

It looks like a few people on stackoverflow get this to work but their code isn't posted. I'm using
[web loadData:data MIMEType:MIMEType textEncodingName:#"UTF-8" baseURL:nil];
where MIMEType is:
#"application/vnd.ms-powerpoint"
#"application/vnd.ms-word"
#"application/vnd.ms-excel"
(BTW, I've seen DOC files use mimetype #"application/msword" but the "vnd" version seems more appropriate. I tried both just in case.)
I verified that my 'data' is correct. PDF and TXT files work. When the UIWebView displays PPT, DOC, or XLS files, it's blank. I put NSLOG statements in my UIWebViewDelegate calls.
shouldStartLoadWithRequest:<NSMutableURLRequest about:blank> navType:5
webViewDidStartLoad:
didFailLoadWithError:Error Domain=NSURLErrorDomain Code=100 UserInfo=0x122503a0 "Operation could not be completed. (NSURLErrorDomain error 100.)"
didFailLoadWithError:Error Domain=WebKitErrorDomain Code=102 UserInfo=0x12253840 "Frame load interrupted"
so obviously the load is failing, but why? If I change my mimetype to #"text/plain" for a PPT file, the UIWebView loads fine and displays unprintable characters, as expected. That's telling me the 'data' passed to loadData: is ok.
Meaning my mimetypes are bad?
And just to make sure my PPT, DOC, and XLS files are indeed ok to display, I created a simple html file with anchor tags to the files. When the html file is displayed in Safari on the iPhone, clicking on the files displays correctly in Safari.
I tried to research the error code displayed in didFailLoadWithError (100) but all the documented error codes are negative and greater than 1000 (as seen in NSURLError.h).
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { NSLog(#"didFailLoadWithError:%#", error); }
Have you tried using the following documented method?:
-(void)loadDocument:(NSString*)documentName inView:(UIWebView*)webView
{
NSString *path = [[NSBundle mainBundle] pathForResource:documentName ofType:nil];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
}
// Calling -loadDocument:inView:
[self loadDocument:#"mydocument.rtfd.zip" inView:self.myWebview];
It works for these in iPhone OS 2.2.1:
Excel (.xls)
Keynote (.key.zip)
Numbers (.numbers.zip)
Pages (.pages.zip)
PDF (.pdf)
Powerpoint (.ppt)
Word (.doc)
iPhone OS 3.0 supports these additional document types:
Rich Text Format (.rtf)
Rich Text Format Directory (.rtfd.zip)
Keynote '09 (.key)
Numbers '09 (.numbers)
Pages '09 (.pages)
The only way i found to read an Office object (tested with .doc or .xls) is to save the NSData object in a temp file, then read it.
-(void)openFileUsingExtension:(NSString*)extension {
NSString *path = [NSString stringWithFormat:#"%#temp.%#",NSTemporaryDirectory(),extension];
NSLog(#"%#",path);
if ([objectFromNSData writeToFile:path atomically:YES]) {
NSLog(#"written");
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webview loadRequest:request];
self.webview.scalesPageToFit = YES;
self.webview.delegate = self;
[self.view addSubview:self.webview];
}
}
then you can remove the file inside the UIWebViewDelegate method:
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSString *path = [NSString stringWithFormat:#"%#temp.%#",NSTemporaryDirectory(),extension];
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}
UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0.0, 0.0, 1000, 760)];
[webView setScalesPageToFit:YES];
webView.backgroundColor=[UIColor clearColor];
NSString *ppt = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"ppt"];
NSURL *pptURL = [NSURL fileURLWithPath:ppt];
NSURLRequest *request = [NSURLRequest requestWithURL:pptURL];
[webView loadRequest:request];
[self.view addSubview:webView];
[webView release];
Did you try this on the device or in the simulator only?
I find that I cannot get UIWebView to display .doc and .pages documents in the simulator (but can display .txt and .pdf ones), but both file types load and display just fine on both the iPad and iPhone devices.
Bug in simulator?
Gregor,
Sweden
After searching thru, the solution I found was because when we import xls into Xcode by drag and drop the xls file into Project->Supporting Files, we need to specific the 'Add to targets:' , we need to tick the project to add