2013-08-18 16 views
1

後點擊了(PDF文件)使用此代碼開放:的iOS - 打開後複製的文件在我的應用

-(BOOL)application:(UIApplication *)application 
     openURL:(NSURL *)url 
    sourceApplication:(NSString *)sourceApplication 
    annotation:(id)annotation { 
if (url != nil && [url isFileURL]) { 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSFileManager *filemgr; 
    NSError *erf; 
    filemgr = [NSFileManager defaultManager]; 
    if ([filemgr copyItemAtPath:[NSString stringWithFormat:@"%@", url] toPath:documentsDirectory error: &erf] == YES) 
     NSLog (@"Copy successful"); 
    else 
     NSLog (@"Copy failed%@dest: %@", erf, url); 
} 
return YES; 

}

我想將文件複製到我的應用程序,但我有此錯誤:

Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x200826c0 {NSFilePath=file://localhost/private/var/mobile/Applications/*.pdf, NSUnderlyingError=0x20082510 "The operation couldn’t be completed. No such file or directory"} Whi?

+1

這與Xcode無關。 – 2013-08-18 18:52:39

回答

1

您不能轉換的NSURL代表使用stringWithFormat:文件URL到NSString。您需要撥打NSURL上的path方法。 toPath:參數需要包含文件名的完整路徑,而不僅僅是要複製到的目錄。

NSString *sourcePath = [url path]; 
NSString *destPath = [documentsDirectory stringByAppendingPathComponent:[url lastPathComponent]]; 

if ([filemgr copyItemAtPath:sourcePath toPath:destPath error:&erf]) { 
+0

是的,它的工作!謝謝 –

0

您可能想考慮將它移動到後臺隊列/線程上,因爲實質上是在您的應用程序被調用時將其鎖定。這有兩個主要副作用

  1. 您的應用在複製操作過程中似乎已掛起,這對用戶體驗來說不會太好。
  2. 如果拷貝時間過長,應用程序將無法響應操作系統,因此操作系統會認爲應用程序已永久掛起,並將終止該應用程序。

我會寫,需要一個URL進行復制的新方法,然後你可以做一些單元測試針對的方法,以確保它是固體,然後安排其到應用程序中的隊列/後臺線程前:的OpenURL :sourceApplication:註解:

相關問題