how to load pdf in binary format on UIWebview iOS? - objective-c

I want to open a pdf file when user clicks on download button, but the data loaded is decode, how can i convert response data to be as a pdf file? i am not loading it from local document or bundle.
NSMutableURLRequest *requestObj = [NSMutableURLRequest requestWithURL:url];
[webViewForDocsView loadRequest:requestObj];
[self.view addSubview:webViewForDocsView];

To load raw data first create a NSData object with the content of the url response, then load the data by specifying the mime type and data, like the code snippet:
NSURL *url = [[NSURL alloc] initWithString:#"binary file link"];
NSError *error;
/**
* GET the data from a url link
*/
NSData *data = [NSData dataWithContentsOfURL:url
options:NSDataReadingUncached
error:&error];
if (error) { // validation
NSLog(#"data error: %#", error);
}
UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.frame];
[self.view addSubview:webView];
/**
* Load the request fro mthe binaray data
*/
[webView loadData:data
MIMEType:#"application/pdf"
textEncodingName:#"utf-8"
baseURL:[NSURL URLWithString:#"http://example.com/"]];

Related

Unable to fetch data from nsurl

NSURL *url = [NSURL URLWithString:[self.imageArray objectAtIndex:indexPath.row]];
NSLog(#"My URL : %#",url);
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(#"New Data : %#",data);
UIImage *tmpImage = [[UIImage alloc] initWithData:data];
cell.imageView.image = tmpImage;
i think i got your problem, check this like my upload image in your project.
i also make a gif about how to add this setting in your project , just follow the step in my gif.

Caching and saving videos in tableview

I'm displaying videos with tableview and would like to save urls/data in cache so user won't have to download the same video again when replayed.
However I'd like to keep them only until user quits the app. The next time he opens the app he'll have to download them again so I only need to save them for the app's active lifetime.
Should I still do caching or is there a more efficient way to do this?
-(void)loadVideo:(NSString *)urlString {
NSURL *url = [NSURL URLWithString:urlString];
NSString* cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* file = [cachePath stringByAppendingPathComponent:#"/EGOCache.plist"];
NSDictionary *dict =[NSDictionary dictionaryWithContentsOfFile:file];
if ([dict objectForKey:urlString] )
{
NSData *data = [[EGOCache globalCache] dataForKey:urlString];
data = [NSURLConnection sendSynchronousRequest:
[NSURLRequest requestWithURL:url]
returningResponse:nil
error:nil];
NSLog(#"loading from cache %#",urlString);
}else{
NSData *data = [NSURLConnection sendSynchronousRequest:
[NSURLRequest requestWithURL:url]
returningResponse:nil
error:nil];
[[EGOCache globalCache] setData:data forKey:urlString];
NSLog(#"saving cache %#",urlString);
}
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval: 10.0];
[self.videoPlayer setContentURL:[request URL]];}
AVFoundation allows for streaming a video file on disk.
I suggest you look into saving the video in the Documents folder or Caches folder and steam it to AVFoundation from there. Then when the user quits the app, applicationWillTerminate gets called and you can wipe the videos from disk.
EDIT
Using MPMoviePlayerController:
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL: URL-TO-FILE-ON-DISK];
[player prepareToPlay];
[player.view setFrame: myView.bounds]; // player's frame must match parent's
[myView addSubview: player.view];
// ...
[player play];

Loading NSData into WebView

I have an NSData object and I want to display it in a WebView. Can WebView handle/display NSData objects?
NSData *data = ... // some data I've gotten from NSURLConnection
WebView *webView = ... [[WebView alloc] init];
Yes!
NSData is handled by UIWebView when properly supplied with MIME type.
This snippet loads a .docx file in a WebView
NSString *path = [urlFileInView path];
NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
webViewForDocsView.delegate = self;
[webViewForDocsView loadData:data MIMEType:#"application/vnd.openxmlformats-officedocument.wordprocessingml.document" textEncodingName:#"UTF-8" baseURL:nil];
Without the Content-Type header, the web view has no way to know how to interpret the data. That's why the Content-Type header was added.
If for some reason you want an NSData capture of network traffic that you can replay whenever you want, consider writing a custom NSURLProtocol. If you write a handler for http then it will override the built-in one; give it a fall-through memory and it can redirect those requests to the real one.
Do it like this
NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
[self.webView loadHTMLString: newStr baseURL:nil];

How can i parse local xml file instead of Web xml in Xcode?

Hii it's easy for me to parse a XML file from a web URL using NSXML Parser but i found little bit difficulty in parsing the local XML file.?
consider this,
my parser.m has a method for
-(void)parseRssFeed:(NSString *)url withDelegate:(id)aDelegate {
[self setDelegate:aDelegate];
responseData = [[NSMutableData data] retain];
NSURL *baseURL = [[NSURL URLWithString:url] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:baseURL];
[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];}
and i used this method for calling a RSS Feed in one of my viewcontroller.m as
- (void)loadData {
if (items == nil) {
[activityIndicator startAnimating];
Parser *rssParser = [[Parser alloc] init];
[rssParser parseRssFeed:#"http://--some RssFeed url---" withDelegate:self];
[rssParser release];
} else {
[self.tableView reloadData];
}
}
and now instead of the some web Rss Feed Url i have to load my local XML file.
Please help me in this coding where i have to change and include NSBundlePath Resource for my local XML FIle.
Thanks in advance!!!
For a local file you don't need the NSURLConnection to get the data. The following will get a local XML file named "local.xml" into an NSData object:
NSString *path = [[NSBundle mainBundle] pathForResource:#"local" ofType:#"xml"];
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
At this point you should be able to call the same parsing code you use once you have the data from the remote xml file.

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.