How to write Dictionary to a file?

前端 未结 1 781
孤独总比滥情好
孤独总比滥情好 2021-02-11 03:49

I have a FileHelper class where I\'ve implemented 3 methods whose job is to write a Dictionary contents to a file. Those methods are:

func storeDictionary(_ dict         


        
1条回答
  •  鱼传尺愫
    2021-02-11 04:36

    First of all filePath?.absoluteString returns the entire – even percent escaped – string including the file:// scheme and the method expects a path without the scheme (filePath?.path - the naming is a bit confusing ;-) ).

    I recommend to save a [String:String] dictionary as property list file. It's not necessary to create the file explicitly.

    I changed the signatures of the methods slightly in the Swift-3-way. Further there is no need to use any optional type.

    func store(dictionary: Dictionary, in fileName: String, at directory: String) -> Bool {
        let fileExtension = "plist"
        let directoryURL = create(directory:directory)
        do {
            let data = try PropertyListSerialization.data(fromPropertyList: dictionary, format: .xml, options: 0)
            try data.write(to: directoryURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension))
            return true
        }  catch {
            print(error)
            return false
        }
    }
    
    func create(directory: String) -> URL {
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        let directoryURL = documentsDirectory.appendingPathComponent(directory)
    
        do {
            try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
        } catch let error as NSError {
            fatalError("Error creating directory: \(error.localizedDescription)")
        }
        return directoryURL
    }
    

    PS: Instead of returning a Bool you could make the store method can throw and handle the error in the calling method:

    func store(dictionary: Dictionary, in fileName: String, at directory: String) throws {
        let fileExtension = "plist"
        let directoryURL = create(directory:directory)
    
        let data = try PropertyListSerialization.data(fromPropertyList: dictionary, format: .xml, options: 0)
        try data.write(to: directoryURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension))
    }
    

    0 讨论(0)
提交回复
热议问题