如何判断文件夹下某个文件是否存在,用fileExistsAtPath:总是NO,文件是存在的

1。应用间资源共享,分享来的文档存在沙盒的Documents/Inbox路径下:
(lldb) po localPath
/var/mobile/Containers/Data/Application/151DF2B1-576C-42B5-8F5D-051132FF2494/Documents/Inbox/%3F%3F%20Microsoft%20Word%20%3F%3F%20(2)-1.docx

这个文件是存在的,但是用我想计算文档大小,用如下方法

NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:localPath]) {
        size = [[fileManager attributesOfItemAtPath:localPath error:nil] fileSize];
    }

总是返回NO,文件不存在,想问下这路径是不是有问题,不能这么判断?
如果路径改为/var/mobile/Containers/Data/Application/151DF2B1-576C-42B5-8F5D-051132FF2494/Documents/Inbox ,就能检测到有文件

在线等~~~
可能问题描述不是很清楚,有时间的可以看下这个http://blog.csdn.net/zhonggaorong/article/details/51832089,我做的就是让第三方app点击“用其他应用打开”,底部弹出的控制台里能有自己的app,然后会跳转到自己app内,回调openUrl:那个方法

阅读 17k
3 个回答

Application/ 后面那一串,应用每次运行都会变的,你不应该把这个路径分享出去,而且一个应用也不能访问到另一个应用的文件目录。

根据iOS App让自己的应用在其他应用中打开列表中显示、iOS把自己的应用添加到”活动“、将PDF文件Open In MyApp

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if (url != nil) {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:url.path]) {
            unsigned long long size = [[fileManager attributesOfItemAtPath:url.path error:nil] fileSize];
            NSLog(@"size:%llu", size);
        }
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        NSLog(@"%@", image);
    }
    
    return YES;
}
  1. 路径中的字符串是每次安装应用时,系统分配的,只要不被卸载,这个路径是不变的
    2.我怀疑是路径名含非法字符导致的问题

3.DOCUMENT目录不是sandbox,就是为分享和云备份,还有iTunes客户端用的

iOS的app都是沙盒,只能访问自己app下的目录。你的app这一串151DF2B1-576C-42B5-8F5D-051132FF2494是会发生变化的。所以要通过相对路径获取。参考代码如下:

NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// 这个documentDirectory就是你的/var/mobile/Containers/Data/Application/151DF2B1-576C-42B5-8F5D-051132FF2494/Documents/目录了
NSString *documentDirectory = [pathArray firstObject];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *localPath = [documentDirectory stringByAppendingPathComponent:@"/Inbox/%3F%3F%20Microsoft%20Word%20%3F%3F%20(2)-1.docx"];
if ([fileManager fileExistsAtPath:localPath]) {
    size = [[fileManager attributesOfItemAtPath:localPath error:nil] fileSize];
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题