You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中fileExists方法检测已存在文件失败问题排查

问题描述

我的应用会创建文件并通过计时器批量处理,但调用fileExists(atPath:)方法时,始终判定目标文件不存在。我在系统文件应用和应用内打印的文档目录文件列表里都能看到该文件,怀疑是误用了fileExists方法。

应用输出:

Creating:
file:///var/mobile/Containers/Data/Application/01793CF4-D50B-4C9D-B4C8-36F916E625BB/Documents/SS-Inventory%20Master%Invoice%2024-08-16gggggg-00000.txt

Checking existence for:
file:///var/mobile/Containers/Data/Application/01793CF4-D50B-4C9D-B4C8-36F916E625BB/Documents/SS-Inventory%20Master%Invoice%2024-08-16gggggg-00000.txt

检测代码:

//Files are created elsewhere within this path
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first


url = manager.urls(for: .documentDirectory, in: .userDomainMask).first
print(url!.path())

@objc func fireTimer() {
    //build filename here
    var invFileName = String(format: "SS-%@-", invoiceName!)
    let curFileTagName = String(format: "%05d", convertCount)
    let curFileLinkName = String(format: "%@%@.txt", invFileName, curFileTagName)

    var checkPath = url

    checkPath!.append(path: curFileLinkName)

    print("Checking existence for:\n\(checkPath!.absoluteString)")

    if FileManager.default.fileExists(atPath: checkPath!.absoluteString) {
        print ("exists yers")
    } else {
        print ("DOESNOTEXISTS")
    }
}
解决方案

你犯了一个常见错误:fileExists(atPath:)需要传入本地文件系统的原生路径字符串,而非URL的absoluteString(带file://前缀和转义字符的URL格式字符串)。

修改判断逻辑,将checkPath!.absoluteString替换为checkPath!.path即可:

if FileManager.default.fileExists(atPath: checkPath!.path) {
    print ("exists yers")
} else {
    print ("DOESNOTEXISTS")
}
原因说明
  • URL.absoluteString返回完整URL字符串,包含file://协议前缀,空格等特殊字符会被转义(比如%20),这不是FileManager能识别的本地路径格式。
  • URL.path返回本地文件系统的原生路径,无协议前缀,特殊字符保持原样,完全匹配fileExists(atPath:)的参数要求。

另外推荐使用更安全的URL直接校验方式,避免路径字符串处理的潜在问题:

var isDirectory: ObjCBool = false
if FileManager.default.fileExists(at: checkPath!, isDirectory: &isDirectory), !isDirectory.boolValue {
    print("exists yers")
} else {
    print("DOESNOTEXISTS")
}

内容的提问来源于stack exchange,提问作者Bartender1382

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 16:40:08