UIwebview doesn't load the PDF file at firdt time - iphone

I am developing one application. In that I'am loading the pdf in uiwebview like below.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filename1 = [[paths objectAtIndex:0] stringByAppendingPathComponent:[default1 objectForKey:#"KeyToSelectedFile"]];
NSString *fileName=[filename1 stringByAppendingPathComponent:[default1 objectForKey:#"keyToAppearfile"]];
NSLog(#"%#",fileName);
//NSString *bookpath=[filename1 stringByAppendingPathComponent:book];
NSURL *url = [NSURL fileURLWithPath:fileName];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
web=[[UIWebView alloc]initWithFrame:CGRectMake(20,80, 980, 690)];
web.delegate=self;
[web loadRequest:request];
web.backgroundColor=[UIColor clearColor];
[self.view addSubview:web];
At first time this will crash the application. From second time onwards it will be showing the pdf correctly. It was not shown any error when the app was crashed. I didn't understand what's the problem.

You can also use Documents interaction controller. it is a better approach to view pdf files using that. and its implementation is quite simple too.
here is a reference link to it: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIDocumentInteractionController_class/Reference/Reference.html
I hope it helps you. Cheers!!
- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL) fileURL
usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate {
UIDocumentInteractionController *interactionController =
[UIDocumentInteractionController interactionControllerWithURL: fileURL];
interactionController.delegate = interactionDelegate;
return interactionController;
}

Just give some time to load the PDF from the web server.. On that loading process u can add a ACTIVITY INDICATOR too...

Related

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];
}

Unable to download whole html page - Objective C/Xcode

I am using the following lines of code to download and save an html page ::
NSURL *goo = [[NSURL alloc] initWithString:#"http://www.google.com"];
NSData *data = [[NSData alloc] initWithContentsOfURL:goo];
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; //Remove the autorelease if using ARC
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSLog(#"%#", documentsDirectory);
NSString *htmlFilePath = [documentsDirectory stringByAppendingPathComponent:#"file.html"];
[html writeToFile:htmlFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
After downloading and saving it, I need to re-use it i.e. upload it. But, I am unable to download the css and image files alongwith the html page i.e. while re-uploading it .. I am not getting the images that should have been displayed on the google home page ..
Can someone help me sort out the issue ?? Thanks and Regards.
The data that is being downloaded is just what the web server returns - pure html. If you need the resources from inside - images/sounds/flash/css/javascripts/etc.. you have parse this html and download all other resources.. Your html may also contain the full path of those resources so you may need to change their urls to be relative (if you want to display it offline or upload it to another server). Parsing can be done with regular expressions or some other 3rd party parsers or libraries that can download the whole web page...
You may take a look at ASIWebPageRequest, which claims to be able to download a whole website, but I haven't tried this functionality...
Use of ASIWebPageRequest will solve problem :
- (void)downloadHtml:(NSURL *)url
{
// Assume request is a property of our controller
// First, we'll cancel any in-progress page load
[[self request] setDelegate:nil];
[[self request] cancel];
[self setRequest:[ASIWebPageRequest requestWithURL:url]];
[[self request] setDelegate:self];
[[self request] setDidFailSelector:#selector(webPageFetchFailed:)];
[[self request] setDidFinishSelector:#selector(webPageFetchSucceeded:)];
// Tell the request to embed external resources directly in the page
[[self request] setUrlReplacementMode:ASIReplaceExternalResourcesWithData];
// It is strongly recommended you use a download cache with ASIWebPageRequest
// When using a cache, external resources are automatically stored in the cache
// and can be pulled from the cache on subsequent page loads
[[self request] setDownloadCache:[ASIDownloadCache sharedCache]];
// Ask the download cache for a place to store the cached data
// This is the most efficient way for an ASIWebPageRequest to store a web page
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[[self request] setDownloadDestinationPath:documentsDirectory] // downloaded path
//[[ASIDownloadCache sharedCache] pathToStoreCachedResponseDataForRequest:[self request]]]; use this instead of documentsDirectory if u want to cache the page
[[self request] startAsynchronous];
}
//These are delegates methods:
- (void)webPageFetchFailed:(ASIHTTPRequest *)theRequest
{
// Obviously you should handle the error properly...
NSLog(#"%#",[theRequest error]);
}
- (void)webPageFetchSucceeded:(ASIHTTPRequest *)theRequest
{
NSString *response = [NSString stringWithContentsOfFile:
[theRequest downloadDestinationPath] encoding:[theRequest responseEncoding] error:nil];
// Note we're setting the baseURL to the url of the page we downloaded. This is important!
[webView loadHTMLString:response baseURL:[request url]];
}
- (void)viewDidLoad {
/// js=yourHtmlSring;
NSString *js; (.h)
[self.myWebView loadHTMLString:js baseURL:nil];
}
//delegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[myWebView stringByEvaluatingJavaScriptFromString:js];
}`
Hey I don't think you can download all the files from google just try with any other url . And you can directly write the NSData to your file htmlFilePath.
[data writeToFile:htmlFilePath atomically:YES];

how do i add html page in my iphone xcode project?

can anyone tell how to add html in my iphone project??
And their is no html option which i click on add new file in class group...why is that???
simply create a blank file and rename it to html or add existing html file to the project.
the next step depends on how you wish to use the html file.
Say if you want to load a local file called page.html, first you add the file to project,and in the build phases of your project, and the page.html to Copy Bundle Resources, and run this in your app, it writes the file to the documents dictionary of your app/
NSString *Html = [[NSString alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"page" ofType:#"html"] encoding:NSUTF8StringEncoding error:NULL];
[Html writeToFile:[[self docPath]stringByAppendingPathComponent:#"page.html"] atomically:YES encoding:NSUTF8StringEncoding error:NULL];
[Html release];
and your webview should call this to load the file:
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [docPaths objectAtIndex:0];
[myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[docPath stringByAppendingPathComponent:#"page.html"]]]];
and it's done.
What you might be looking for is documentation and example code for the UIWebView class of UIKit.
You can use UIWebView to show your html file like this
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
[webView loadRequest:request];
where URLString contains is your file url.

How to read a pdf on ipad/iphone?

What is the way to read PDF content on an iPad or iPhone?
You can use Quartz to parse a PDF document and extract the metadata.
Parsing a PDF
There is another simple way to read a PDF in iPhone/iPad:
Take one UIwebView (name:pdfView).
Give Iboutlet connection to it & Delegate it to FilesOwner
In Viewdidload/VIewWillApper/VIewDidApper
[self.pdfView loadRequest:[NSURLRequest requestWithURL:
[NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"ObjC" ofType:#"pdf"]]]];
ObjC.pdf should be in resource folder
Use fastpdfkit: https://github.com/mobfarm/FastPdfKit
Firstly, save a built in pdf file in document Directory of iPhone Simulator (say it demo.pdf). then use following code in ViewController.m file at ViewDidLoad method and dont forget to add UIWebViewDelegate in ViewController.h file
-(void) viewDidLoad
{
[super viewDidLoad];
UIWebView theWebView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
theWebView.delegate=self;
theWebView.scalesPageToFit=YES;
[self.view addSubview:theWebView];
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir=[paths objectAtIndex:0];
NSString *fileName=[documentDir stringByAppendingPathComponent:#"demo.pdf"];
NSURL *url=[NSURL fileURLWithPath:fileName];
[theWebView loadRequest:[NSURLRequest requestWithURL:url]];
}

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];