Programmatically download html page - Objective C/Xcode - iphone

I have a button called "Download page" at the bottom of my detailView of SplitView app in iPad. I want to download the corresponding html page on the click of the aforementioned button i.e. I need to add the functionality of the "Ctrl+S" for that button so that I could download and save the page. How can I do that ?

You should do this:
//Download data from URL
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"yourstringURL"]];
//use this data to write to any path as documentdirectory path + filename.html
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//create file path
NSString *htmlFilePath = [documentsDirectory stringByAppendingPathComponent:#"file.html"];
//write at file path
BOOL isSucess = [data writeToFile:htmlFilePath atomically:YES];
if (isSucess)
NSLog(#"written");
else
NSLog(#"not written");
You can same htmlFilePath to retrieve html file from document directory

You can get all the html content inside an NSString and then save it, like so
NSString *allHtml = [webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.outerHTML"];
[allHtml writeToFile:#"YourFilePath" atomically:YES encoding:NSUTF8StringEncoding error:NULL];
This will save all the HTML to the path you define

Related

How to Convert string-> pdf

i'm working with web services that returns a base64 string representing a pdf file.
I am able to decode that string into NSData but how to show that into pdf.
Is there any way to store that data as a .pdf file and show it in application.
Any ideas on how I can go about this? I have looked at a few posts and still can't seem to figure it out.
Any idea's appreciated, thanks :)
First you need to save the data into a file, then load it into a webview
- (void)DisplayPdf:(NSData *)pdfContent
{
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:#"myPdf.pdf"];
NSURL *url = [NSURL fileURLWithPath:finalPath];
[pdfContent writeToURL:url atomically:YES];
[aWebView loadRequest:[NSURLRequest requestWithURL:url]];
}

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.

Saving a file to a user's device where the webview can see it

I have a hybrid (Objective C + HTML) application and I would like to be able to periodically save a remote file (images and css) to a user's device but in such a way that it can be loaded by a browser within a webview instance in the same application.
I don't think it's possible to save files to the resource bundle itself (though in the simulator you can), so I assume I would have to save the file somewhere else. But I'm not sure what path to use where the HTML document could still access it.
Basically, I'd like to do something like this:
NSURL* url = [NSURL URLWithString:#"http://myserver.com/August.png"];
NSString* filePath = #"[?????]/MonthlyImage.png";
NSData* data = [NSData dataWithContentsOfURL:url];
if (data)
{
NSError* error;
if ([data writeToFile:filePath options:NSDataWritingAtomic error:&error])
{
NSLog(#"Wrote");
}
if (error != nil)
{
NSLog(#"ERROR: %#", [error description]);
}
}
Then in my webview, I'd like to be able to load the image like this:
<img src="[??????]/MonthlyImage.png" />
What values can I use in place of the ?????? that will work? Is it even possible?
Saving to the bundle is not allowed because it is not allowed to modify the app binary.
You could try and store the file in the documents folder, then retrieve it from there. The important point, to make it work, is specifying also a baseURL when creating the UIWebVIew.
You can retrieve the documents directory in this way:
NSString *documentsDirectory = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
if ([paths count] > 0) {
documentsDirectory = [paths objectAtIndex:0];
}
Then you store there your file, and when you want to load it in your UIWebView, execute:
[_label loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:documentsDirectory]];
Now, <img src="MonthlyImage.png" /> will look for the png in your documents directory.

can i generate a text file from my iphone application

Hi
I am creating a simple calculation based application and at end i need to create a text file for the calculation made in that app.Now i want that whole result into the text file, i dont if we can create a text file through our application or not but need to create that and also if we are able to create it then can we transfer to our pc/mac .
If any tutorial is available it would be of great help .
Regards
Mrugen
Try:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:#"myfile.conf"];
NSString *settings = #"1.0,0.0,0.0,0,";
NSData* settingsData;
settingsData = [settings dataUsingEncoding: NSASCIIStringEncoding];
if ([settingsData writeToFile:filePath atomically:YES])
NSLog(#"writeok");
Taken from: http://sio2interactive.forumotion.net/t347-how-to-write-a-text-file-to-iphone#1847

Loading a web page in iphone and check history

Pseudo code
pageUrl = "http://www.google.com"
if(pageUrl == never Downloaded)
Download pageUrl
else
{
Display Saved Version
Mean while download pageUrl
When done display new version
}
How can I do something like this in objective C for a UIWebview?
Also what's the best way to save web pages for this scenario? PList, SQLite?
Plist is the best way to solve your problem.
iPhone/Objective-c can access very quickly to plist file as compare to SQLite Database.
Let me give you some sample code.
See - edit After some time.
Edit :
Steps for Creating project & connecting web-view
Create New Project -> View Based Application.
Give name "yourProjName" ( up to you what you give )
Open "yourProjNameViewController.xib"
Drag & drop UIWebView
Open "yourProjNameViewController.h" File
Place a variable IBOutlet UIWebView *wView;
Connect in interface builder
Steps for adding Property list file to your project
Expand Resources Group under your project tree
Right click on "Resources" -> Add -> New File
Select Template Category - osx -> Resource
Select Property List file
Give file name "LoadedURL.plist"
Change Root type to Array
Save "LoadedURL.plist" file
Now place following code to "yourProjNameViewController.m" file.
#import "yourProjNameViewController.h"
#define documentsDirectory_Statement NSString *documentsDirectory; \
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); \
documentsDirectory = [paths objectAtIndex:0];
#implementation WebViewLoadViewController
- (void)viewDidLoad {
[super viewDidLoad];
// your url to load
NSString *strToLoad=#"http://www.mail.yahoo.com";
// file management code
// copy file to documents directory
documentsDirectory_Statement;
NSFileManager *fm=[NSFileManager defaultManager];
if(![fm fileExistsAtPath:[documentsDirectory stringByAppendingPathComponent:#"LoadedURL.plist"]]){
[fm copyItemAtPath:[[NSBundle mainBundle] pathForResource:#"LoadedURL" ofType:#"plist"]
toPath:[documentsDirectory stringByAppendingPathComponent:#"LoadedURL.plist"]
error:nil];
}
// array from doc-dir file
NSMutableArray *ar=[NSMutableArray arrayWithContentsOfFile:[documentsDirectory stringByAppendingPathComponent:#"LoadedURL.plist"]];
// check weather file has url data or not.
BOOL fileLocallyAvailable=NO;
NSString *strLocalFileName=nil;
NSUInteger indexOfObject=0;
if([ar count]>0){
for (NSDictionary *d in ar) {
if([[d valueForKey:#"URL"] isEqualToString:strToLoad]){
fileLocallyAvailable=YES;
strLocalFileName=[d valueForKey:#"FileName"];
break;
}
indexOfObject++;
}
}
if(fileLocallyAvailable){
NSDictionary *d=[ar objectAtIndex:indexOfObject];
strLocalFileName=[d valueForKey:#"FileName"];
} else {
NSMutableDictionary *d=[NSMutableDictionary dictionary];
[d setValue:strToLoad forKey:#"URL"];
NSString *str=[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:strToLoad]];
[str writeToFile:[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%02i.htm",[ar count]]]
atomically:YES
encoding:NSUTF8StringEncoding error:nil];
strLocalFileName=[NSString stringWithFormat:#"%02i.htm",[ar count]];
[d setValue:[NSString stringWithFormat:#"%02i.htm",[ar count]] forKey:#"FileName"];
[ar addObject:d];
[ar writeToFile:[documentsDirectory stringByAppendingPathComponent:#"LoadedURL.plist"]
atomically:YES];
}
NSURL *u=[[NSURL alloc] initFileURLWithPath:[documentsDirectory stringByAppendingPathComponent:strLocalFileName]];
NSURLRequest *re=[NSURLRequest requestWithURL:u];
[wView loadRequest:re];
[u release];
}
`