我在UIWebView和UIButton中显示PDF文件列表。当我单击按钮时,我需要将我的PDF文件保存到iBooks,以后用户可以从iBooks阅读。

这是我的代码如下:

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:

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{

}

最佳答案

您必须为此使用UIDocumentInteractionController

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


希望这会帮助你。

关于ios - 将PDF文件保存到iBooks。,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22291683/

10-11 00:22