[英]iOS - copy file after open in my app
單擊打開后(pdf文件),代碼如下:
-(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;
}
我想將文件復制到我的應用程序,但出現此錯誤:
錯誤域= NSCocoaErrorDomain代碼= 260“無法完成操作。(可可錯誤260。)” UserInfo = 0x200826c0 {NSFilePath = file:// localhost / private / var / mobile / Applications / * .pdf,NSUnderlyingError = 0x20082510 “操作無法完成。沒有這樣的文件或目錄”}嗨?
您不能使用stringWithFormat:
將表示文件URL的NSURL
轉換為NSString
。 您需要在NSURL
上調用path
方法。 並且toPath:
參數必須是包含文件名的完整路徑,而不僅僅是您要復制到的目錄。
NSString *sourcePath = [url path];
NSString *destPath = [documentsDirectory stringByAppendingPathComponent:[url lastPathComponent]];
if ([filemgr copyItemAtPath:sourcePath toPath:destPath error:&erf]) {
您可能想考慮將其移至后台隊列/線程,因為在調用應用程序時,您實際上是在鎖定應用程序。 這有兩個主要的副作用
我將編寫一個新方法,該方法采用URL進行復制,然后可以對該方法進行一些單元測試以確保其牢固,然后再將其調度到應用程序中的隊列/后台線程中:openURL:sourceApplication:annotation:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.