save Webview Data offline mode - ios

when there are connection i load data from the url direct , if there are no Internet i get the data from cache (offline mode) i wrote this code
NSURL *url = [NSURL URLWithString:_url];
NSURLRequest * reqyest = [NSURLRequest requestWithURL:url];
if ([[NSUserDefaults standardUserDefaults]objectForKey:#"data"]) {
NSData * yourData = [[NSUserDefaults standardUserDefaults]objectForKey:#"data"];
NSString *html = [[NSString alloc] initWithData:yourData encoding:NSUTF8StringEncoding];
[_webview loadHTMLString:html baseURL:nil];
NSLog(#"iam here");
}
else
{ [_webview loadRequest:reqyest];
NSCachedURLResponse* response = [[NSURLCache sharedURLCache]
cachedResponseForRequest:reqyest];
NSData* data = [response data];NSLog(#"%#",data);
[[NSUserDefaults standardUserDefaults]setObject:data forKey:#"data"];
[[NSUserDefaults standardUserDefaults]synchronize];
NSLog(#"herer erege");
}

Related

how to cache html5 File(UIWebView)

I use the UIWebView to load the URL which is a HTML5 application.
What I want to do is cache the HTML file,when there is no net connection,it load the cache.
when the connection can be use,it load the URL again to see if there has new data
you can try something like this:
#define APP_PATH_HTML_PAGES_CACHE [[NSHomeDirectory() stringByAppendingPathComponent:#"Library/Caches"] stringByAppendingPathComponent:#"html_pages_cache"]
- (void)setUrlString:(NSString *)urlString{
if (![_urlString isEqualToString:urlString]) {
NSURL *url = nil;
_urlString = urlString;
NSString *fileName = [self fileNameFromUrl:_urlString];
if(isInternetConnected){//load page and store on file system
url = [NSURL URLWithString:_urlString];
[self downloadPageWithName:fileName andUrl:url];//download to cache
}else{
//network is not available, check for cached file
if ([self isFileExistInCacheDirectory:fileName]) {
url = [NSURL fileURLWithPath:[APP_PATH_HTML_PAGES_CACHE stringByAppendingPathComponent:fileName]];
}
else {
//TODO: show offline/error alert
}
}
//load local or remote page
// here url can point to local file or web page
NSURLRequest* request = [[NSURLRequest alloc]initWithURL:url];
//to be sure that view components did initialized.
if ([self view]) {
[self.webView loadRequest:request];
}
}
- (void)downloadPageWithName:(NSString*)fileName andUrl:(NSURL*)url
{
`dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self checkIsCacheDirectoryExistOrCreate];`
NSString *filePath = [APP_PATH_HTML_PAGES_CACHE stringByAppendingPathComponent:fileName];
NSData *data = [NSData dataWithContentsOfURL:url];
[data writeToFile:filePath atomically:YES];
NSLog(#"Download: %# -> %#", url.absoluteString, filePath);
});
}

Image download failed with url iOS

I am trying to download my image and store into a directory. Every thing is working fine before updating the names of images on the server end with spaces. I am handling the spaces with the following code.
NSString *newString = [getImageUrl stringByReplacingOccurrencesOfString:#" "
withString:#"%20"];
After that I am getting the final String of URL as given below
http://www.retail-king.com/image/data/men%20jeans/pd%201/5.jpg
When I open this url in browser then the image is showing but I cannot see and download the image with this url in the app.
I am calling the following method to download the image.
-(void)downloadImageWithPath:(NSString *)_path andURL:(NSString *)_url
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:_url]];
NSLog(#"pic file = %#",_path);
NSLog(#"ASI http pic url:%#",[[request url] description]);
// [request setDownloadProgressDelegate:self];
[request setShowAccurateProgress:YES];
request.shouldContinueWhenAppEntersBackground=YES;
[request setDownloadDestinationPath:_path];
[request setTimeOutSeconds:30];
// [request setDelegate:self];
[request setStartedBlock:^{
NSLog(#"request started pic");
}];
[request setCompletionBlock:^{
// Use when fetching text data
NSLog(#"request completed pic");
currentPicsCount++;
if (currentPicsCount == picsCount && totalPicsDownload ) {
NSLog(#"All pics have downloaded");
totalPicsDownload = false;
[[SingltonClass getLoadingClassReference] dataSynced];
}
}];
[request setFailedBlock:^{
NSLog(#"request failed pic");
picsCount--;
}];
[request startAsynchronous];
}
setFailedBlock is called. Which shows pic is failed to download.
Your question is ambiguous. I quickly ran a test on the URL and was able to see the downloaded image. This might not be an ideal solution, but you can understand what's going on. I used UIWebView to display the image, and the for you the tricky part could be to set the bounds of CGRectMake. How are you downloading and displaying the images?
Here is my code if it helps.
- (void)viewDidLoad
{
[super viewDidLoad];
// Added space between keyword men and jeans
NSString *url = #"http://retail-king.com/image/data/men jeans/pd%201/5.jpg";
url = [url stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
// Check for URL
NSLog(#"Final Url = %#",url);
// Displaying it on webview
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
NSURL *targetURL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
// Program to check if the image is downloaded in directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *localFilePath = [paths objectAtIndex:0];
NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
[thedata writeToFile:localFilePath atomically:YES];
}
The image was successfully downloaded at -
/Users/raurora/Library/Application Support/iPhone Simulator/7.1/Applications/554A5C94-1D29-42F0-886D-751CD3DFB155/Library/Caches/com.stackoverflow.doubt/fsCachedData/

Get title of a website silently from a website

I have a link of a website, and I want to get its title.
I tried to do by this code
UIWebView* hiddenWebView;
NSString* urlString = #"http://www.youtube.com/watch?v=OyORxdjGtlk";
NSURL* url = [NSURL URLWithString:urlString];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[hiddenWebView loadRequest:request];
NSString* text = [hiddenWebView stringByEvaluatingJavaScriptFromString:#"document.title"];
But the result is: text = NULL;
I just want to get the name of the video
Set the UIWebView delegate to your ViewController (for example by ctrl-dragging in Interface Builder) and then:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSURL *url = [webView.request mainDocumentURL];
NSString *str = [url absoluteString];
NSString *title = [webView stringByEvaluatingJavaScriptFromString:#"document.title"];
NSLog(#"%s: url=%# str=%# title=%#", __PRETTY_FUNCTION__, url, str, title);
}

UIWebView Not Loading View

My UIWebView doesn't seem to be loading:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *urlAddress = [defaults stringForKey:#"webPage"];
NSLog(#"%#", urlAddress);
NSURLRequest *requestObj = [NSURLRequest requestWithURL:[NSURL URLWithString:urlAddress]];
webView.delegate = self;
[webView loadRequest:requestObj];
}
It is in a UIViewController (connected through IB) and urlAddress returns google.com
Can you check if the URL being fetched is valid?
NSString *urlAddress = [defaults stringForKey:#"webPage"];
NSLog(#"%#", urlAddress);
NSURL *u = [NSURL URLWithString:urlAddress];
if(u){
NSURLRequest *requestObj = [NSURLRequest requestWithURL:u];
webView.delegate = self;
[webView loadRequest:requestObj];
}else{
[[[UIAlertView alloc] initWithTitle:#"" message:#"invalid url." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil] show];
}
google.com is not a valid url, it should be http://www.google.com. So maybe that is the issue here.
Try this code:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
webView.delegate = self;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *urlAddress = [defaults stringForKey:#"webPage"];
NSLog(#"%#", urlAddress);
[self openURLFromString:urlAddress];
}
- (void) openURLFromString:(NSString*) urlString
{
NSURL *url = [self validateAddress:urlString];
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
[webView loadRequest:request];
}
- (NSURL*) validateAddress:(NSString*) address
{
NSURL* result = [NSURL URLWithString:address];
if (!result.scheme)
{
NSString* modifiedURLString = [NSString stringWithFormat:#"http://%#", address];
result = [NSURL URLWithString:modifiedURLString];
}
return result;
}
#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSMutableURLRequest *)urlRequest navigationType:(UIWebViewNavigationType)navigationType
{
return YES;
}
You're missing base URL part of the URL ( Click here to read more about this ), which is necessary.
So try this:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *urlAddress = [defaults stringForKey:#"webPage"];
NSString * theURL = [NSString stringWithFormat:#"http://%#", urlAddress]; // you can also use stringByAppendingString if you prefer
NSLog(#"%#", theURL);
NSURLRequest *requestObj = [NSURLRequest requestWithURL:[NSURL URLWithString:theURL]];
webView.delegate = self;
[webView loadRequest:requestObj];
}
HTH :)

Failed to download and open a PDF file with error failed to find PDF header in ios

I am having an app in which I am opening a PDF file from a url.
I am successfully able to open it in a webView.
Now I want to download that PDF file and save it in my documents folder and want to send that PDF file in my mail.
I searched a lot and found the best solution below.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"myfile.pdf"];
if(![[NSFileManager defaultManager] fileExistsAtPath:filePath]){
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.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];
[webView setUserInteractionEnabled:YES];
[webView setDelegate:self];
webView.scalesPageToFit = YES;
[webView loadRequest:requestObj];
But when i try this code, it gives me error saying failed to find PDF header: `%PDF' not found
I am even not able to open my PDF also.
I know same questions are asked before but I am not able to solve this error right now.
I don't know what I am doing wrong over here.
Sorry for the inconvenience.
Please help me with this.
try this code for downloading & saving your pdf file
UIActivityIndicatorView *indicator=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[indicator startAnimating];
NSLog(#"Downloading Started");
NSString *urlToDownload = #"http://gradcollege.okstate.edu/sites/default/files/PDF_linking.pdf";
NSURL *url = [NSURL URLWithString:urlToDownload];
NSURLRequest *request=[[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLCacheStorageAllowed timeoutInterval:120.0f];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
[indicator stopAnimating];
if (!connectionError) {
if ( data )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"myfile.pdf"];
//saving is done on main thread
dispatch_async(dispatch_get_main_queue(), ^{
[data
writeToFile:filePath atomically:YES];
NSLog(#"File Saved !");
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_rssWebView setUserInteractionEnabled:YES];
//[_rssWebView setDelegate:self];
[_rssWebView loadRequest:requestObj];
});
}
}
}];
If convert to string server response, that you got in NSData *pdfData, you will see next:
<!DOCTYPE html>
<html>
<head>
<title>iOS Developer Library</title>
<meta charset="utf-8">
<script>
var content_page = "navigation";
var href = window.location.href;
if (window.location.href.match('#')) {
var newhref = href.replace('#', '');
newhref = newhref.replace('%23', '#');
window.location.href = newhref;
}
else {
console.log(content_page);
console.log(content_page.match("content_page"));
if(content_page.match("content_page")) {
window.location.href = './navigation';
}
else {
window.location.href = "./" + content_page;
}
}
</script>
</head>
<body>
</body>
<script type="text/javascript" src="/library/webstats/pagetracker.js"></script>
<script type="text/javascript">
if(typeof PageTracker !== 'undefined') {
if(window.addEventListener) {
window.addEventListener("load", function(){PageTracker.logPageLoad()},false);
} else if(window.attachEvent) {
window.attachEvent("onload",function(){PageTracker.logPageLoad()});
}
}
</script>
</html>
This only web page, which, as I can assume, will forward you to document with another URI:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf. So you must use this url if you want to download .pdf file
Also, pay attention on #pawan's answer, and use his approach to avoid download files in main thread

Resources