Xcode - 从 NSDocumentDirectory 路径获取文件



我从我的网络视图生成了一个多页pdf,我想通过ActivityViewController共享pdf文件。我只有文件路径,不知道如何访问文件以让他们通过活动视图控制器共享。

CGRect origframe = webView.frame;
NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"]; // Get the height of our webView
int height = [heightStr intValue];
// Size of the view in the pdf page
CGFloat maxHeight   = 568;
CGFloat maxWidth    = webView.frame.size.width;
int pages = ceil(height / maxHeight);
// gets the total no:of pages needed in PDF
[webView setFrame:CGRectMake(0.f, 0.f, maxWidth, maxHeight)];
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString *pdfFileName = [documentDirectory stringByAppendingPathComponent:@"mypdf.pdf"];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
int i = 0;
for ( ; i < pages; i++)
{
if (maxHeight * (i+1) > height)
{ // Check to see if page draws more than the height of the UIWebView
CGRect f = [webView frame];
f.size.height -= (((i+1) * maxHeight) - height);
[webView setFrame: f];
}
// Specify the size of the pdf page
CGRect PDFRect = CGRectMake(0, 0, webView.frame.size.width, webView.frame.size.height);
UIGraphicsBeginPDFPageWithInfo(PDFRect, nil);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
// Move the context for the margins
CGContextScaleCTM(currentContext, 1, 1);
// offset the webview content so we're drawing the part of the webview for the current page
[[[webView subviews] lastObject] setContentOffset:CGPointMake(0, maxHeight * i) animated:NO];
// draw the layer to the pdf, ignore the "renderInContext not found" warning.
[webView.layer renderInContext:currentContext];
}
// all done with making the pdf
UIGraphicsEndPDFContext();
// Restore the webview and move it to the top.
[webView setFrame:origframe];
[[[webView subviews] lastObject] setContentOffset:CGPointMake(0, 0) animated:NO];

如何共享完成的文件?

提前感谢!

你应该把你的文件网址放到 UIActivityViewController 中

NSString * title =[NSString stringWithFormat:@"Some title string", pdfFileName];
NSArray* pdfToShare = @[title];
UIActivityViewController* activityViewController =[[UIActivityViewController alloc] initWithActivityItems:pdfToShare applicationActivities:nil];
[self presentViewController:activityViewController animated:YES completion:^{}];

更新:

https://developer.apple.com/documentation/foundation/nsdata/1547245-datawithcontentsofurl

NSError* error = nil;
NSData* data = [NSData dataWithContentsOfURL: pdfFileName options:NSDataReadingUncached error:&error];
if (error) {
NSLog(@"%@", [error localizedDescription]);
} else {
// make some stuff with pdf data
}

最新更新