gpt4 book ai didi

ios - Swift 3.0 FileManager.fileExists(atPath :) always return false

转载 作者:IT王子 更新时间:2023-10-29 05:04:19 26 4
gpt4 key购买 nike

当我使用方法.fileExists(atPath:)判断文件是否存在于文件系统中时,该方法总是返回false给我。我检查了文件系统,文件确实存在。这是我的代码:

let filePath = url?.path
var isDir : ObjCBool = false
if(self.fileManager.fileExists(atPath: filePath!, isDirectory: &isDir)){
let result = NSData(contentsOfFile: filePath!)
}

let filePath = url?.path
if(self.fileManager.fileExists(atPath: filePath!)){
let result = NSData(contentsOfFile: filePath!)
}

if 子句将始终被跳过。

最佳答案

我假设您的 urlURL 类型。如果是这样,试试这个:

let filePath = url?.path  // always try to work with URL when accessing Files
if(FileManager.default.fileExists(atPath: filePath!)){ // just use String when you have to check for existence of your file
let result = NSData(contentsOf: url!) // use URL instead of String
}

说够了,你应该像这样改变你的实现:

if(FileManager.default.fileExists(atPath: (url?.path)!)){  // just use String when you have to check for existence of your file
let result = NSData(contentsOf: url!) // use URL instead of String
}

编辑:1

还有更好的方法,你可以称之为 swift-way (:D)。您不必显式检查文件是否存在

guard let result = NSData(contentsOf: fileURL) else {
// No data in your fileURL. So no data is received. Do your task if you got no data
// Keep in mind that you don't have access to your result here.
// You can return from here.
return
}
// You got your data successfully that was in your fileURL location. Do your task with your result.
// You can have access to your result variable here. You can do further with result constant.
print(result)

没有 Objective-Cish NS 前缀的 Swift 3.0+ 更新:

do {
let result = try Data(contentsOf: fileURL)
print(result)
} catch {
print(error)
}

关于ios - Swift 3.0 FileManager.fileExists(atPath :) always return false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42897844/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com