【问题标题】:iOS - copy file after open in my appiOS - 在我的应用程序中打开后复制文件
【发布时间】:2013-08-18 18:51:14
【问题描述】:

使用此代码在(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;

}

我想将文件复制到我的应用程序,但出现此错误:

Error Domain=NSCocoaErrorDomain Code=260 “操作无法完成。(Cocoa 错误 260。)” UserInfo=0x200826c0 {NSFilePath=file://localhost/private/var/mobile/Applications/*.pdf, NSUnderlyingError=0x20082510 "操作无法完成。没有这样的文件或目录"} 什么?

【问题讨论】:

  • 这与Xcode无关。

标签: ios cocoa-touch


【解决方案1】:

您不能使用 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]) {

【讨论】:

    【解决方案2】:

    您可能想要考虑将其移至后台队列/线程,因为您实际上是在调用应用程序时锁定了它。这有两个主要的副作用

    1. 在复制操作期间,您的应用似乎已挂起,这不利于用户体验。
    2. 如果复制时间过长,应用程序将无法响应操作系统,因此操作系统会认为应用程序已永远挂起并将其终止。

    我会编写一个新方法,它需要一个用于复制的 URL,然后您可以对该方法进行一些单元测试以确保它是可靠的,然后再将其调度到应用程序中的队列/后台线程:openURL:sourceApplication:注释:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-17
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      相关资源
      最近更新 更多