Save Data to .plist File in Swift

前端 未结 7 1340
一整个雨季
一整个雨季 2020-11-27 18:10

I am trying to save data to a plist file in swift, but the data isn\'t showing up as it was saved when the plist is read. This is the code I was using.

var          


        
7条回答
  •  温柔的废话
    2020-11-27 18:30

    struct Plist {
    
    enum PlistError: ErrorType {
        case FileNotWritten
        case FileDoesNotExist
    }
    
    let name:String
    
    var sourcePath:String? {
        guard let path = NSBundle.mainBundle().pathForResource(name, ofType: "plist") else { return .None }
        return path
    }
    
    var destPath:String? {
        guard sourcePath != .None else { return .None }
        let dir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
        return (dir as NSString).stringByAppendingPathComponent("\(name).plist")
    }
    
    init?(name:String) {
    
        self.name = name
    
        let fileManager = NSFileManager.defaultManager()
    
        guard let source = sourcePath else { return nil }
        guard let destination = destPath else { return nil }
        guard fileManager.fileExistsAtPath(source) else { return nil }
    
        if !fileManager.fileExistsAtPath(destination) {
    
            do {
                try fileManager.copyItemAtPath(source, toPath: destination)
            } catch let error as NSError {
                print("Unable to copy file. ERROR: \(error.localizedDescription)")
                return nil
            }
        }
    }
    
    
    func getValuesInPlistFile() -> NSDictionary?{
        let fileManager = NSFileManager.defaultManager()
        if fileManager.fileExistsAtPath(destPath!) {
            guard let dict = NSDictionary(contentsOfFile: destPath!) else { return .None }
            return dict
        } else {
            return .None
        }
    }
    
    func getMutablePlistFile() -> NSMutableDictionary?{
        let fileManager = NSFileManager.defaultManager()
        if fileManager.fileExistsAtPath(destPath!) {
            guard let dict = NSMutableDictionary(contentsOfFile: destPath!) else { return .None }
            return dict
        } else {
            return .None
        }
    }
    
    func addValuesToPlistFile(dictionary:NSDictionary) throws {
        let fileManager = NSFileManager.defaultManager()
        if fileManager.fileExistsAtPath(destPath!) {
            if !dictionary.writeToFile(destPath!, atomically: false) {
                print("File not written successfully")
                throw PlistError.FileNotWritten
            }
        } else {
            throw PlistError.FileDoesNotExist
        }
    }
    }
    

    Now, implement below in your view controller.

            if let plist = Plist(name: "plist file name") {
            let dict = plist.getMutablePlistFile()!
            dict["key"] = value
    
            do {
                try plist.addValuesToPlistFile(dict)
            } catch {
                print(error)
            }
                print(plist.getValuesInPlistFile())
            } else {
               print("Unable to get Plist")
            }
    

提交回复
热议问题