Xcode-从NSDocumentDirectory路径获取文件

时间:2018-09-16 18:49:37

标签: ios xcode

我从Web视图生成了多页pdf,我想通过ActivityViewController共享pdf文件。我只有文件路径,不知道如何访问文件以使它们通过ActivityViewController共享。

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

如何共享完成的文件?

谢谢!

1 个答案:

答案 0 :(得分:0)

您应该将文件网址放入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
}