美文网首页
Swift之PlistUtil存储工具

Swift之PlistUtil存储工具

作者: wasdzy111 | 来源:发表于2018-11-12 17:44 被阅读0次

直接上工具类

import Foundation
class PlistUtil {
    func put(fileName:String,key:String,val:String) -> Bool {
        do{
            //获得存储路径
            let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
            //拼接名字
            let fileName = "\(path!)/\(fileName).plist"
            let dic:NSDictionary = [key:val]
            //写入
            return dic.write(toFile: fileName, atomically: true)
        }catch{
            return false
        }
    }
    func get(fileName:String,key:String) -> String {
        //获得数据存储路径
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        let fileNameRel = "\(path!)/\(fileName).plist"
        //判断文件是否存在
        let fileManager = FileManager.init()
        let exist = fileManager.fileExists(atPath: fileNameRel)
        if !exist{
            //print("你查询的文件不存在")
            return ""
        }
        //读取plist:如果有数返回数据 否则返回默认 ""
        let dicRes = NSDictionary.init(contentsOfFile: fileNameRel)
        if dicRes != nil{
            let res = dicRes?[key]
            return res as? String ?? ""
        }else{
            return ""
        }
    }
}

测试类

        let plist  = PlistUtil.init()
        //测试写入
        let flag =  plist.put(fileName: "mplist", key: "initsqlitedata2", val: "zheng")
        if flag {
            print("写入数据成功")
        }else{
            print("写入数据失败")
        }
        //测试读取
        let res =  plist.get(fileName: "mplist", key: "initsqlitedata2")
        if res == ""{
            print("没有获取到数据")
        }else{
            print("===> \(res)")
        }

相关文章

网友评论

      本文标题:Swift之PlistUtil存储工具

      本文链接:https://www.haomeiwen.com/subject/mnicfqtx.html