首页 > 解决方案 > Xcode - 从 NSDocumentDirectory 路径获取文件

问题描述

我从我的网络视图生成了一个多页 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];

如何共享完成的文件?

提前致谢!

标签: iosxcode

解决方案


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

推荐阅读