I'm displaying list of PDF files in UIWebView along with UIButton. When I click the button I need to save my PDF file to iBooks and later user can read from iBooks.
Here is my code below:
NSString *path = [[NSBundle mainBundle] pathForResource:#"mypdf" ofType:#"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
UIWebView *webView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
[[webView scrollView] setContentOffset:CGPointMake(0,500) animated:YES];
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:#"window.scrollTo(0.0, 50.0)"]];
[webView loadRequest:request];
[self.view addSubview:webView];
[webView release];
UIButton for download:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(download:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[webView addSubview:button];
-(void)download:(id)sender{
}
You have to use UIDocumentInteractionController for this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *pdfFilePath = [documentsDir stringByAppendingPathComponent:yourPdfFile.pdf];// your yourPdfFile file here
NSURL *url = [NSURL fileURLWithPath:pdfPath];
UIDocumentInteractionController *docController = [UIDocumentInteractionController interactionControllerWithURL:url];
docController.delegate = self;
[docController retain];
// docController is released when dismissed (autorelease in the delegate method)
BOOL isValid = [docController presentOpenInMenuFromRect:yourReadPdfButton.frame inView:self.view animated:YES]; // Provide where u want to read pdf from yourReadPdfButton
if (!isValid) {
NSString * messageString = [NSString stringWithFormat:#"No PDF reader was found on your device. In order to consult the %#, please download a PDF reader (eg. iBooks).", yourPDFFileTitle];
UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:messageString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
...
// UIDocumentInteractionController delegate method
- (void)documentInteractionControllerDidDismissOpenInMenu:(UIDocumentInteractionController *)controller {
[controller autorelease];
}
Hope this will help you.
Related
I want to load a gif image with webView,And it works well.But when i find leaks with instruments,there is a memory leak. Who can tell me why,Here is the code:
NSString *path = [[NSBundle mainBundle] pathForResource:#"icon_coinMoney_image" ofType:#"gif"];
UIWebView *gifWebView = ({
UIWebView *webView = [UIWebView new]; //Leaks Here
[self addSubview:webView];
[webView setBackgroundColor:[UIColor clearColor]];
webView.userInteractionEnabled = NO;
[webView setScalesPageToFit:YES];
webView.opaque = NO;
NSURL *url = [NSURL URLWithString:path];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
[webView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(backImageView.mas_left).offset(-MARGIN);
make.centerY.mas_equalTo(backImageView.mas_centerY).offset(1.f);
make.size.mas_equalTo(CGSizeMake(ZLL_AUTOSIZING_WIDTH(30.f), ZLL_AUTOSIZING_HEIGTH(30.f)));
}];
[webView.layer setMasksToBounds:YES];
[webView.layer setCornerRadius:ZLL_AUTOSIZING_WIDTH(15.f)];
webView;
});
I have custom cell with button. When tap on button I download video from server. During download I need to show activity indicator, but it does not show activityindicatorview.
Code:
RBFriendChatTableViewCell *Cell = [ tableView dequeueReusableCellWithIdentifier:Identifier];
[Cell.m_btnDownLoad addTarget:self action:#selector(downLoadImage:) forControlEvents:UIControlEventTouchUpInside];
-(void)downLoadImage:(UIbutton *)sender{
indicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
indicator.center = CGPointMake(5, 5);
[sender addSubview:indicator];
[indicator startAnimating]
NSString *strUrl = [NSString stringWithFormat:#"%#%#",chatImage,[dicChatList objectForKey:#"file"]];
NSURL *url=[[NSURL alloc] initWithString:strUrl];
NSData *movieData = [NSData dataWithContentsOfURL:url];
NSURL *fileURL = [self grabFileURL:[dicChatList objectForKey:#"file"]];
[movieData writeToURL:fileURL atomically:YES];
[m_arrDownloadVideoName addObject:[dicChatList objectForKey:#"file"]];
}
You need to update the UI in main thread, you are downloading the video in the same thread, it should be done in a background Asynch thread, for your current situation following fix might help but its best to do the downloading in background and update the UI once its done.
-(void)downLoadImage:(UIbutton *)sender{
dispatch_async(dispatch_get_main_queue(), ^{
indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle : UIActivityIndicatorViewStyleGray];
indicator.center = CGPointMake(5, 5);
[sender addSubview:indicator];
[indicator startAnimating];
});
NSString *strUrl = [NSString stringWithFormat:#"%#%#",chatImage,[dicChatList objectForKey:#"file"]];
NSURL *url=[[NSURL alloc] initWithString:strUrl];
NSData *movieData = [NSData dataWithContentsOfURL:url];
NSURL *fileURL = [self grabFileURL:[dicChatList objectForKey:#"file"]];
[movieData writeToURL:fileURL atomically:YES];
[m_arrDownloadVideoName addObject:[dicChatList objectForKey:#"file"]];
}
in my application I manage to post an image to Instagram through a Document Interaction Controller. This one shows also options for sharing on Dropbox, whatsapp, etc.. I don't want these features, I just want Instagram. Is there a way to programmatically click on Instagram button, or to remove other unwanted applications' buttons?
Thank you in advance for your answers.
EDIT: Here is the code, with the line containing "com.instagram.exclusivegram" I managed to show only Instagram, Bump and Dropbox. How can I make the last two disappear?
-(void)ShareInstagram
{
[self storeimage];
NSURL *instagramURL = [NSURL URLWithString:#"instagram://app"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL])
{
CGRect rect = CGRectMake(0 ,0 , 612, 612);
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/15717.igo"];
NSURL *igImageHookFile = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:#"file://%#", jpgPath]];
_dic.UTI = #"com.instagram.exclusivegram";
_dic.delegate=self;
_dic = [self setupControllerWithURL:igImageHookFile usingDelegate:self];
_dic=[UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];
_dic.delegate=self;
[_dic presentOpenInMenuFromRect: rect inView: self.view animated: YES ];
// [[UIApplication sharedApplication] openURL:instagramURL];
}
else
{
// NSLog(#"instagramImageShare");
UIAlertView *errorToShare = [[UIAlertView alloc] initWithTitle:#"Instagram unavailable " message:#"You need to install Instagram in your device in order to share this image" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
errorToShare.tag=3010;
[errorToShare show];
}
}
- (void) storeimage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"15717.igo"];
UIImage *NewImg=[self resizedImage:_imageToTweet inImage:CGRectMake(0, 0, 612, 612) ];
NSData *imageData = UIImagePNGRepresentation(NewImg);
[imageData writeToFile:savedImagePath atomically:NO];
}
- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate
{
UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL:fileURL];
interactionController.delegate = self;
return interactionController;
}
The method setupControllerWithURL:usingDelegate overwrites properties of _dic instance variable set above.
These lines has no effect:
_dic.UTI = #"com.instagram.exclusivegram";
_dic.delegate=self;
First instantiate UIDocumentInteractionController, then set its properties:
NSURL *igImageHookFile = [NSURL URLWithString:[NSString stringWithFormat:#"file://%#", jpgPath]];
_dic = [UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];
_dic.UTI = #"com.instagram.exclusivegram";
_dic.delegate = self;
[_dic presentOpenInMenuFromRect:rect inView:self.view animated:YES];
Basically, I want to click a button in my web view that will download a PDF from a remote website and display it with a close/back button. I'm using QLViewController so people can pinch-zoom the PDF, and I'm using PhoneGap 3.0 with XCode 5 to code it.
Here's the code for my plugin that will show the new view with the back button but I can't seem to get the PDF to show. Any ideas?
#import "PDFViewer.h"
#import <Cordova/CDV.h>
#implementation PDFViewer
- (void)loadRemotePdf:(CDVInvokedUrlCommand*)command
{
CDVPluginResult* pluginResult = nil;
NSString *website = [command.arguments objectAtIndex:0];
NSString *filename = [command.arguments objectAtIndex:1];
if (website != nil && [website length] > 0) {
CGRect rect = [[UIScreen mainScreen] bounds];
CGSize screenSize = rect.size;
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)];
webView.autoresizesSubviews = YES;
[webView canGoBack];
webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// NSURL *myUrl = [NSURL URLWithString:website];
// NSURLRequest *myRequest = [NSURLRequest requestWithURL:myUrl];
// [webView loadRequest:myRequest];
// [window addSubview: webView];
NSURL *url = [NSURL URLWithString:website];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, filename];
[urlData writeToFile:filePath atomically:YES];
// Create test view controller
QLPreviewController *previewer = [[QLPreviewController alloc] init];
previewer.dataSource = self;
previewer.delegate = self;
// Create navigation controller
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:previewer];
[window addSubview: [nav view]];
[window makeKeyAndVisible];
}
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
}
else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
}
// return result
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
#pragma mark - QLPreviewControllerDataSource
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
return 1;
}
- (id <QLPreviewItem>) previewController: (QLPreviewController *) controller previewItemAtIndex: (NSInteger) index;
{
NSURL *fileURL = [NSURL fileURLWithPath: filePath];
return fileURL;
}
#end
Yes, this can be done with the UIWebView.
If you are trying to display a PDF file residing on a server somewhere, you can simple load it to your web view directly:
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];
NSURL *targetURL = [NSURL URLWithString:#"http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
[webView release];
//Or if you have a PDF file bundled with your application (in this example named "document.pdf"):
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];
NSString *path = [[NSBundle mainBundle] pathForResource:#"document" ofType:#"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
[webView release];
I have loaded a PDF file in a UIWebView from the resource bundle.
Now, I am not able to zoom/pinch the PDF file.
I found the below 2 relevant links, but none of the answers are marked as correct -
How to zoom webView with pdf file
Enable zooming/pinch on UIWebView
How to make the PDF zoomable/pinchable which has been loaded in a UIWebView from the resource bundle, Will the below solution work ?
Problem with pdf while opening in UIWebView
Thanks for your help.
In your WebView on Interface Builder add check to Scale Page To Fit and you enable a Pinch ZoomIn ZoomOut ;)
Or if you want to lad better your PDF try to Look this code:
- (void)viewDidLoad
{
[super viewDidLoad];
[webView loadRequest:[NSURLRequest requestWithURL:#"http:pdfURL"]];
NSString *path = [[NSBundle mainBundle] pathForResource:#"yourPDFFile" ofType:#"pdf"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
//--------------AND HERE USE SCALE PAGE TO FIT------------------//
[webView setScalesPageToFit:YES];
}
Hope this help you.
//Try like this
NSString *urlstr=#"www.example.com/yy.pdf";
web=nil;
web=[[UIWebView alloc] initWithFrame:CGRectMake(0, 98, 320, 367)];
web.delegate=self;
[self.view addSubview:web];
[web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlstr]]];
UIPinchGestureRecognizer *pgr = [[UIPinchGestureRecognizer alloc]
initWithTarget:self action:#selector(handlePinch:)];
pgr.delegate = self;
[web addGestureRecognizer:pgr];
// Target Action
- (IBAction)handlePinch:(UIPinchGestureRecognizer *)recognizer
{
recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);
recognizer.scale = 1;
}
Before this add UIGestureRecognizerDelegate in .h. Hope it will helps you..
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:documentsDirectory])
{
NSURL *url = [NSURL fileURLWithPath:strFileName];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView setScalesPageToFit:YES];
[webview loadRequest:request];
}