UIDocumentInteractionController for remote pdf files - iphone

Does anybody know how to use UIDocumentInteractionController to "Open in iBooks" remote pdf files, i can't seem to be able to get around this one. I have managed to open my pdf in QLPreviewController and get the OptionsMenu to give me the option to open in iBooks but i won't open the file if it is remote...when i use local file it works fine.
If this is not possible what is the alternative?
Thanks in advance

Although UIDocumentInteractionController has a convenience method interactionControllerForURL:, it requires the argument to be a file URL. So you either download the PDF within your app and open it with the UIDocumentInteractionController object or you can use a UIWebView object to open remote PDFs. Pass the URL to the web view and they open just fine.

Ad mentioned you must use a file url for UIDOcumentInteractionController. First download the document. A really easy way to do this is with AFNetworking. Here is how I am using AFNetworking to download a file:
- (BOOL)webView:(UIWebView *)theWebView shouldStartLoadWithRequest:(NSURLRequest *)req navigationType:(UIWebViewNavigationType)navigationType {
self.title = req.URL.description;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = req.URL;
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];
self.fileURLPath = [documentsDirectoryPath URLByAppendingPathComponent:[response suggestedFilename]];
return self.fileURLPath;
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(#"File downloaded to: %#", filePath);
}];
[downloadTask resume];
return YES;
}
Now that you have the fileURLPath you can create the UIDocumentInteractionController like so:
documentController = [UIDocumentInteractionController interactionControllerWithURL:self.fileURLPath];

Related

Video download from HTML + UIWebView

In my new application i need to download video from different-different web sites, Say it is video downloader application. For this what i am planing is Searching html for .mp4 and .Flv url and then trying to downloading videos. There are many app already doing same
http://itunes.apple.com/in/app/video-downloader-super-lite/id481701140?mt=8
What i am asking is, how can we download video? Any code or link or something. how this application work ? Any Help will really appreciate.
what i needed is when you open a page in UIWebview Say you open "www.youtube.com" and select a video to play then it ask to download. For download i need URL (Embeded url, Flv url, mpv url) so i can paas this to function. I need to know about That URL
If you are able to use the AFNetworking library, it's pretty simple. You can make an HTTP request and use its outputStream property to download the file to your device. Say you hook up a download button to a function downloadVideoFromURL:withName:
- (void)downloadVideoFromURL:(NSURL*)url withName:(NSString*)videoName
{
//filepath to your app's documents directory
NSString *appDocPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *videosPath = [appDocPath stringByAppendingPathComponent:#"Videos"];
NSString *filePath = [videosPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.mp4", videoName]];
//check to make sure video hasn't been downloaded already
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
//file was already downloaded
}
//video wasn't downloaded, so continue
else
{
//enable the network activity indicator
[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
//create a temporary filepath while downloading
NSString *tmpPath = [videosPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#-tmp.mp4", videoName]];
//the outputStream property is the key to downloading the file
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:tmpPath append:NO];
//if operation is completed successfully, do following
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//rename the downloaded video to its proper name
[[NSFileManager defaultManager] moveItemAtPath:tmpPath toPath:filePath error:nil];
//disable network activity indicator
[AFNetworkActivityIndicatorManager sharedManager].enabled = NO;
//optionally, post a notification to anyone listening that the download was successful
[[NSNotificationCenter defaultCenter] postNotificationName:#"DownloadedVideo" object:nil];
//if the operation fails, do the following:
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", error);
//delete the downloaded file (it is probably partially downloaded or corrupt)
[[NSFileManager defaultManager] removeItemAtPath:tmpPath error:nil];
//disable network activity indicator
[AFNetworkActivityIndicatorManager sharedManager].enabled = NO;
}];
//start the operation
[operation start];
}
}
if you really want to go for hacking , you you will get apple's private library, "webkit" , if you try to find the subviews of UIWebview, it might help you, i never tried it, but you can test with this logic.

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

iPhone's Pasteboard not recognizing a URL

I want my app to recognize if the current contents of the Clipboard are a URL, and if it is, I want it to load that URL into a web-view.
I'm using the following statement to do this checking:
if ([pasteboard containsPasteboardTypes: [NSArray arrayWithObject:#"public.url-name"]])
...code to load the URL into the webView
but its not working - the IF statement always returns as FALSE, even when the clipboard's contents are clearly a URL.
Strangely enough though, when I remove this IF statement and just go ahead and load the URL I read from the Clipboard into the webView it works perfectly well. So its definitely just the IF statement that's not working for some reason.
Here's the full code:
// executed on a Button-click:
-(IBAction) showClipBoard {
pasteboard = nil; // resetting the pasteBoard each time
pasteboard = [UIPasteboard generalPasteboard];
NSURL *tempURL = pasteboard.URL;
//Check the pasteboard's value-type:
if ([pasteboard containsPasteboardTypes: [NSArray arrayWithObject:#"public.url-name"]]) {
NSLog(#"URL is: %#", pasteboard.string);
NSURL *url = [NSURL URLWithString: pasteboard.string];
NSURLRequest *req = [NSURLRequest requestWithURL: url];
[webView loadRequest:req];
}
else
NSLog(#"=NOT a valid web-address");
NSString *tempString = [pasteboard valueForPasteboardType:#"public.utf8-plain-text"];
// Show the URL in a text-view box called "clipText":
clipText.text = tempString;
}
Anyone see what's wrong here?
You've probably figured this out by now, but, I ran into the same issue & the following worked for me :-
if ([pasteboard containsPasteboardTypes: [NSArray arrayWithObject:#"public.url"]])
...code to load the URL into the webView

UIWebView links opening in Safari

I want to open an iTunes link in my webView, but when the webView launches the page, it redirects to the Safari browser. There, the url is getting opened, but I want it to open in my webView.
- (void)viewDidLoad {
NSString *urlAddress = #"http://itunes.apple.com/us/app/foodcheck-traffic-light-nutrition/id386368933?mt=8";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];
//URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webView loadRequest:requestObj];
[super viewDidLoad];
}
Please suggest a way to sort out this problem.
You may want to try logging the load requests when you run the app. It may be that apple is automatically changing http:// to itms-apps or http://phobos or something along these lines. If so, then you can block the load when it's call using something like this:
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType;
{
NSURL *loadURL = [[request URL] retain];
NSLog(#"%#",loadURL);
if([[loadURL absoluteString] hasPrefix:#"http://"])
{
[loadURL release];
return TRUE;
}
[loadURL release];
return FALSE;
}
Good luck. I'm curious to know what finally works.
A note from the Apple reference documents- Q: How do I launch the App Store from my iPhone application? Also, how do I link to my application on the store?
Note: If you have iTunes links inside
a UIWebView, you can use this
technique after intercepting the links
with the -[UIWebViewDelegate webView:shouldStartLoadWithRequest:navigationType:]
delegate method.
Not sure if you ever got it working, but this works well for me:
NSString *responseString = [NSString stringWithContentsOfURL:myURL];
[self.webView loadHTMLString:responseString baseURL: nil)];

Cookies don't work in UIWebView displaying "local content"

There are a lot of threads about using UIWebView with caches and/or cookies, but they all seem to relate to remote URLs.
I cannot get cookies to work when "displaying local content" (as the iPhone docs call it).
For example, if I load a plain old HTML file from my bundle resource:
- (void) viewDidLoad {
[super viewDidLoad];
NSString* path = [[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"];
NSURL* url = [NSURL fileURLWithPath:path];
NSData* data = [NSData dataWithContentsOfFile:path];
[web loadData:data MIMEType:#"text/html" textEncodingName:#"us-ascii" baseURL:url];
}
then:
- (void) webViewDidFinishLoad:(UIWebView*)webView {
NSString* result = [web stringByEvaluatingJavaScriptFromString:
#"try{document.cookie='name=value';''+document.cookie;}catch(e){''+e}"];
NSLog(#"Result = '%#'", result);
}
results in:
Result = ''
Setting the URL to be the actual filename rather than the directory prevents getting: Result = 'Error: SECURITY_ERR: DOM Exception 18', but the cookies do not seem to persist.
I have found a satisfactory work-around. By specifying a real URL, such as http://localhost/..., and then intercepting the loading, by subclassing the NSURLCache class, in order to fetch actual local content.
- (NSCachedURLResponse*) cachedResponseForRequest:(NSURLRequest *)request {
NSString* path = [[request URL] path];
NSData* data = [... get content of local file ...];
NSURLResponse *response = [[NSURLResponse alloc]
initWithURL:[request URL]
MIMEType:[self mimeTypeForPath:path]
expectedContentLength:[data length]
textEncodingName:nil];
NSCachedURLResponse* cachedResponse = [[NSCachedURLResponse alloc]
initWithResponse:response
data:data];
[response release];
return [cachedResponse autorelease];
}
Well you could check out NSHTTPCookieStorage class reference. But If you're using the webView for local content, what is the purpose of using cookies? Why not just save that info some other way on your app?
If your aim is to store data in the UIWebView you can also use window.localStorage. It is a hashtable in which you can store max. 5MB of string data.
e.g.
window.localStorage['highscore_level_1']='12000';
alert(window.localStorage['highscore_level_1']);
I've used this succesfully to implement a highscore table in an UIWebView based iPhone App.