J'ai une classe FileHelper dans laquelle j'ai implémenté 3 méthodes dont le rôle est d'écrire le contenu d'un dictionnaire dans un fichier. Ces méthodes sont :
func storeDictionary(_ dictionary: Dictionary<String, String>, inFile fileName: String, atDirectory directory: String) -> Bool {
let ext = "txt"
let filePath = createFile(fileName, withExtension: ext, atDirectory: directory)
/**** //If I use this method, file is created and dictionary is saved
guard (dictionary as NSDictionary).write(to: filePath!, atomically: true) else {
return false
}
*/
guard NSKeyedArchiver.archiveRootObject(dictionary, toFile: (filePath?.absoluteString)!) else {
return false
}
return true
}
func createFile(_ file: String, withExtension ext: String, atDirectory directory: String) -> URL? {
let directoryPath = createDirectory(directory)
let filePath = directoryPath?.appendingPathComponent(file).appendingPathExtension(ext)
if !FileManager.default.fileExists(atPath: (filePath?.absoluteString)!) {
let success = FileManager.default.createFile(atPath: (filePath?.absoluteString)!, contents: nil, attributes: nil)
print("\(success)") //** here is the issue I investigated. Always prints false.
}
return filePath
}
func createDirectory(_ directory: String) -> URL? {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let directoryPath = documentsDirectory.appendingPathComponent(directory)
do {
try FileManager.default.createDirectory(at: directoryPath, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
fatalError("Error creating directory: \(error.localizedDescription)")
}
return directoryPath
}
Quand j'appelle FileHelper().storeDictionary(aValidDictionary, inFile: "abc", atDirectory: "XYZ")
pour écrire le dictionnaire, il échoue avec cette procédure. Mais si j'utilise
guard (dictionary as NSDictionary).write(to: filePath!, atomically: true) else {
return false
}
ça marche.
Quel est le problème avec NSKeyedArchiver.archiveRootObject(_:toFile:)
méthode ?
Et pourquoi FileManager.default.createFile(atPath: (filePath?.absoluteString)!, contents: nil, attributes: nil)
retourne toujours faux ?