在模拟器中使用UIDocumentInteractionController

时间:2012-12-04 11:31:14

标签: ios ios-simulator share

我对UIDocumentInteractionController非常绝望。我唯一想做的就是从我的应用程序与所有其他注册PDF的应用程序共享我的pdf文件。

这是我的代码:

NSString * filePath = [[NSBundle mainBundle] pathForResource:@"Sample" ofType:@"pdf"];
self.docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
self.docController.delegate = self;

NSURL *url = [NSURL fileURLWithPath:filePath];
BOOL isValid = [[UIApplication sharedApplication] canOpenURL:url];
NSLog(@"uti: %@", [self.docController UTI]);

//[self.docController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
[self.docController presentOpenInMenuFromBarButtonItem:self.backBut animated:YES];

isValid变量始终为TRUE,UTI记录为com.adobe.pdf(这似乎是正确的)但调用presentOpenFrom...两个调用(一个已注释)始终返回NO。

我正在用模拟器测试,那是问题吗?有没有人看到代码有问题或者知道要检查什么?

3 个答案:

答案 0 :(得分:1)

如果您正在处理PDF文件,那么您应该有任何能够在您的设备(模拟器)上打开PDF文件的应用程序。 您可能希望安装PDF File Viewer,因为它是开源的。 通过从Xcode运行安装应用后,您的UIDocumentInteractionController将正确显示。

以下是从网上下载任何文档并提交UIDocumentInteractionController以将其传递给其他应用程序的示例代码。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [paths objectAtIndex:0];
BOOL isDir = NO;
NSError *error;
if (! [[NSFileManager defaultManager] fileExistsAtPath:cachePath isDirectory:&isDir] && isDir   == NO)
{
    [[NSFileManager defaultManager] createDirectoryAtPath:cachePath withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *filePath = [cachePath stringByAppendingPathComponent:url.lastPathComponent];
NSData *fileData = [NSData dataWithContentsOfURL:url];
[fileData writeToFile:filePath atomically:YES];
NSURL *filePathURL = [NSURL fileURLWithPath:filePath];
self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:filePathURL];
[self.documentInteractionController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];

答案 1 :(得分:0)

试试这个:

NSString* path = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"pdf"];
if (path) {
    NSURL* url = [NSURL fileURLWithPath:path];
    UIDocumentInteractionController* docController = [UIDocumentInteractionController interactionControllerWithURL:url];
    docController.delegate = self;
    [docController presentPreviewAnimated:YES];
}

答案 2 :(得分:0)

Kenney的解决方案仍然正确如果此实现所需的全部内容是PDF的预览。但是,它并没有解决presentOpenInMenuFromRect或presentOpenInMenuFromBarButtonItem的原始问题。这只会在预览中显示pdf而不是实际的“Open In ...”对话框。除了使用设备启动Open In控制器之外,没有已知的解决方案。

presentOpenInMenu ...方法检查系统以查看是否已下载任何已注册的PDF阅读器。由于iOS模拟器不提供一个,并且无法添加一个,因此只能在设备上测试此功能。