2012-12-04 28 views
0

我非常絕望UIDocumentInteractionController。我唯一想做的事情就是從我的應用程序與所有其他註冊爲PDF的應用程序共享我的PDF文件。在模擬器中使用UIDocumentInteractionController

這是我的代碼:

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變量始終是真實的,UTI記錄爲com.adobe.pdf(這似乎是正確的),但調用presentOpenFrom...兩個電話(一個評論)總是返回NO。

我正在用模擬器測試,是這個問題嗎?有人看到代碼有問題,或者有什麼想法檢查什麼?

回答

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

肯尼的解決方案仍然是正確的是PDF的預覽。但是,它不能解決presentOpenInMenuFromRect或presentOpenInMenuFromBarButtonItem的原始問題。這隻會在預覽中顯示PDF,而不是實際的「打開在...」對話框。除了使用設備調出Open In控制器之外,還沒有已知的解決方案。

presentOpenInMenu ...方法檢查系統,看看是否有任何已註冊的PDF閱讀器已下載。由於iOS模擬器不提供一個,因此無法添加一個,因此只能在設備上測試此功能。

+1

你可以很容易地在模擬器中,可以打開PDF文件... – omz

+0

有趣添加一個「虛擬」的應用程序,實際上從未嘗試過這一點。如果可行,獲得開源PDF閱讀器應該非常簡單。這已得到證實嗎? –

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