Swift 3.0 FileManager.fileExists(atPath:) всегда возвращает false
Когда я использую метод .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 всегда будет пропущено.
Ответы
Ответ 1
Я предполагаю, что ваш url
является типом url
. Если да, попробуйте это:
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
}
EDIT: 1
Есть еще лучший способ, вы можете назвать его быстрым (: 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)
Ответ 2
в быстро 3
на всякий случай, если кто-то запутается, как я, вот полные фрагменты:
let str = "file:///Users/martian2049/Library/Developer/CoreSimulator/Devices/67D744AA-6EEC-4AFD-A840-366F4D78A18C/data/Containers/Data/Application/DD96F423-AF9F-4F4D-B370-94ADE7D6D0A5/Documents/72b8b0fb-7f71-7f31-ac9b-f9cc95dfe90d.mp3"
let url = URL(string: str)
print(url!.path,"\n")
if FileManager.default.fileExists(atPath: url!.path) {
print("FILE Yes AVAILABLE")
} else {
print("FILE NOT AVAILABLE")
}
это печатает
/Users/martian2049/Library/Developer/CoreSimulator/Devices/67D744AA-6EEC-4AFD-A840-366F4D78A18C/data/Containers/Data/Application/DD96F423-AF9F-4F4D-B370-94ADE7D6D0A5/Documents/72b8b0fb-7f71-7f31-ac9b-f9cc95dfe90d.mp3
FILE Yes AVAILABLE
Обратите внимание, что "file://
" отрублено?
Ответ 3
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true);
var path = paths[0] as String;
path = path + "/YourFilePath"
if((NSFileManager.defaultManager().fileExistsAtPath(path))) {
let result = NSData(contentsOfFile: filePath!)}
Попробуйте приведенный выше код и еще раз проверьте
Ответ 4
- Во-первых, как выглядит ваш путь к файлу? Если путь начинается с символа ~, то он должен быть расширен с помощью
expandingTildeInPath
;
- Проверьте, недоступен ли путь к вашему приложению. Приложение iOS может посещать только свои песочницы.