plist文件路径 swift

2018-07-26 22:10:08 u011865919 阅读数 1059

在MacOS项目中使用Swift管理plist,实现读写plist文件。

1. Jobs.swift
使用Jobs类管理Jobs.plist

//  Jobs.swift
//  Created by Cyril on 18/7/11.
//  Copyright © 2018年 GJ. All rights reserved.
import Foundation
class Jobs: NSObject {
    var RestoreSequence_1: Dictionary<String , AnyObject?> = [:]
    var RestoreSequence_2: Dictionary<String , AnyObject?> = [:]
    var RestoreSequence_3: Dictionary<String , AnyObject?> = [:]
    let dModel = DataModel()
    //构造方法
    override init(){
        super.init()
        print("[Jobs] 初始化...")
        onCreateData("Jobs.plist")
        let d = dModel.loadData("Jobs", dFilePath: "Jobs.plist")
        let skey:String = "RestoreStage"
        print("查找\(skey)结果:\(dModel.searchValueByKey(d, skey: skey))")
    }
    func onCreateData(fileName: String){
        print("[Jobs]: 开始创建plist文件")
        //Document path   本地数据数据路径   .plist格式
        let fileManager = NSFileManager.defaultManager()
        let localDataPath:String = dModel.dataFilePath(fileName)
        print("[Jobs]: " + localDataPath)
        var isLocalDataExisted = fileManager.fileExistsAtPath(localDataPath)
        print("isLocalDataExisted->\(isLocalDataExisted)")

        //判断.plist文件是否存在
        if isLocalDataExisted == false//文件不存在
        {
            fileManager.createFileAtPath(localDataPath, contents: nil, attributes: nil)//创建.plist文件
        }
        isLocalDataExisted = fileManager.fileExistsAtPath(localDataPath)
        print("isLocalDataExisted->\(isLocalDataExisted)")

        //设置root
        let root = NSMutableDictionary()
        //设置dictionay
        root.setValue(
            [
                "RestoreSequence_1":[
                    "RestoreStage" : "P1",
                    "Input_Type" : "Uart_Diags",
                    "TempValues" : [
                        "MLBSN" : "#ProgramWriteToIt#",
                        "FGSN" : "#ProgramWriteToIt#",
                        "Mod#" : "#ProgramWriteToIt#",
                        "Regn" : "#ProgramWriteToIt#",
                    ],
                    "Command_Device" : [
                        "TTPowerSupply" : "#TT治具上电命令#",
                        "MLBSN" : "syscfg print MLB#",
                        "Write_FGSN" : "sn #FGSN#",
                        "Print_FGSN" : "sn",
                        "Write_Mod" : "syscfg add Mod# #Mod##",
                        "Print_Mod" : "syscfg print Mod#",
                        "Write_Regn" : "syscfg add Regn #Regn#",
                        "Print_Regn" : "syscfg print Regn",
                        "LogCollection" : "#LogCollection#",
                        "Restart" : "#TT治具重新上电命令#"
                    ],
                    "Command_Host" : [
                        "暂时为空" : "暂时为空"
                    ]
                ],
                "RestoreSequence_2":[
                    "RestoreStage" : "P2",
                    "Input_Type" : "Uart_iBoot",
                    "TempValues" : [
                        "MLBSN" : "#ProgramWriteToIt#",
                        "FGSN" : "#ProgramWriteToIt#",
                        "#暂时为空#" : "#暂时为空#",
                    ],
                    "Command_Device" : "#暂时为空#",
                    "Command_Host" : [
                        "暂时为空" : "暂时为空"
                    ]
                ],
                "RestoreSequence_FG":[
                    "RestoreStage" : "FG",
                    "Input_Type" : "Uart_OS",
                    "TempValues" : [
                        "FGSN" : "#ProgramWriteToIt#",
                        "#暂时为空#" : "#暂时为空#",
                    ],
                    "Command_Device" : "#暂时为空#",
                    "Command_Host" : [
                        "暂时为空" : "暂时为空"
                    ]
                ],

            ], forKey: "Jobs")
        //将root写入.plist文件
        root.writeToFile(localDataPath, atomically: true)
        isLocalDataExisted = fileManager.fileExistsAtPath(localDataPath)
        if isLocalDataExisted == true{
            print("[Jobs]: Jobs.plist文件创建完成")
        }else{
            print("[Jobs]: Jobs.plist文件创建失败")
        }
        /*  try! fileManager.removeItemAtPath(localDataPath)//删除本地数据文件 */
    }    
}

2. DataModel.swift

//  DataModel.swift
//  Created by Cyril on 18/7/11.
//  Copyright © 2018年 GJ. All rights reserved.

import Foundation
class DataModel: NSObject {
    var userList = [UserInfo]()
   // var keyArray: Dictionary = [Int: String] ()
    //获取沙盒文件夹路径
    func documentsDirectory()->String {
        /*  let paths = NSSearchPathForDirectoriesInDomains(
         NSSearchPathDirectory.DocumentationDirectory,NSSearchPathDomainMask.UserDomainMask,true)
         let documentsDirectory:String = paths.first! as String */
        let path = "./Cyril/Anole"
        return path
    }

    /**
     获取数据文件地址
     Eg:
     fileName:userList.plist
     */
    func dataFilePath (fileName: String)->String{
        print(documentsDirectory().stringByAppendingString("/" + fileName))
        return documentsDirectory().stringByAppendingString( "/\(fileName)")
    }

    /**
     读取数据
     Eg:
     key: userList
     dFilePath: userList.plist
     */
    func loadData(key: String, dFilePath: String)-> NSDictionary{
        //判断.plist文件是否存在
        let fileManager = NSFileManager.defaultManager()
        let isLocalDataExisted = fileManager.fileExistsAtPath(self.dataFilePath(dFilePath))
        print("isLocalDataExisted->\(isLocalDataExisted)")
        if isLocalDataExisted == false//文件不存在
        {
            fileManager.createFileAtPath(self.dataFilePath(dFilePath), contents: nil, attributes: nil)//创建.plist文件
        }
        let dicFromPList: NSDictionary? = NSDictionary(contentsOfFile: "/Users/coreos/Desktop/Cyril/Anole/Jobs_P1P2FG.plist")
        print("文件 " + dFilePath + " 读取完成")
        return dicFromPList!
    }

    /**
     * 通过key查找在字典中的value值
     */
    func searchValueByKey(dic: NSDictionary, skey: String)-> String{
        var printHead = "[searchValueByKey]: "
        if (dic.count == 0){
            return printHead + "输入的参数字典为空"
        }
        //plist 四层结构遍历(尚有bug未更正)
        for (key1, value1) in (dic as! NSMutableDictionary) {
      //      keyArray.updateValue(key as! String, forKey: 1)
            print("第1层->字典 key \(key1) -  字典 value () \(value1)")
            if(key1 as! String == skey){
                print("\(printHead)\(skey)查找成功, 为根字典")
                return "查找的\(skey)的值为\(value1)"
            }
            for (key2, value2) in (value1 as! NSMutableDictionary) {
                print("第2层->字典 key \(key2) -  字典 value \(value2)")
                if(key2 as! String == skey){
                    print("\(printHead)\(skey)查找成功, 在字典\(key1)下")
                    return "查找的\(skey)的值为\(value2)"
                }
                for (key3, value3) in (value2 as! NSMutableDictionary) {

                    print("第3层->字典 key \(key3) -  字典 value \(value3)")
                    if(key3 as! String == skey){
                        print("\(printHead)\(skey)查找成功, 在字典\(key2)下")
                        return "查找的\(skey)的值为\(value3)"
                        for (key4, value4) in (value3 as! NSMutableDictionary) {

                            print("第4层->字典 key \(key4) -  字典 value \(value4)")
                            if(key4 as! String == skey){
                                print("\(printHead)\(skey)查找成功, 在字典\(key3)下")
                                return "查找的\(skey)的值为\(value4)"
                            }
                        }
                    }
                }
            }
        }
        return "\(printHead)输入的参数字典为空"
    }

    /**
     *  值类型判断
     */
    func judgeValueType(dic: AnyObject) -> String{
        if let dict1 = dic as? NSMutableDictionary{
            return "NSMutableDictionary"
        }else if let dict1 = dic as? NSDictionary{
            return "NSDictionary"
        }else if let dict1 = dic as? NSArray{
            return "NSArray"
        }else if  let dict1 = dic as? NSValue{
            return "NSValue"
        }else{
            return "\(dic)" //其他可能是字串类型
        }
    }
}
2019-08-23 14:59:46 T_Tzz 阅读数 340

1、新建

在新建文件的类型中,选择Property List文件,新建即可。

2、读取

let unit_path = Bundle.main.path(forResource: "文件名(xxx)", ofType: "plist(文件类型)")  //获取此文件所在的路径
let unit_data:NSMutableDictionary = NSMutableDictionary.init(contentsOfFile: unit_path!)!  //获取文件的路径,获取文件的类型,我的例子是字典型(有字典型和数组型可选)
let unit_String = unit_data["key"]! as! String   //利用键-值对的方式,进行存取

注:此语句必须写到一个函数中,不能写成全局变量

3、存储

save_data.setObject(value, forKey: "key" as NSCopying)  //save_data是根据路径,得到的文件对象。 "key"为文件对象中的键,“value”为你想为此key设置的值
save_data.write(toFile: save_path!, atomically: true)   //此步极为重要,前面设置的键值对设置只是保留在内存中,需要这句话,来写入到文件中

 

2018-07-27 10:52:52 weixin_41735943 阅读数 2064

plist文件的读写这部分有个坑,在Xcode中创建的plist文件在代码运行时是只读的,你可以正确写入读出,但是无法持久化存储。如果想做持久化,必须用代码在沙箱目录中创建plist文件。因为Xcode创建的plist文件和程序代码同级,就如同你无法在运行时修改程序代码。

读取Xcode中手动创建的Plist文件

//生成文件的存储路径
let plistPath = Bundle.main.path(forResource: "demoPlist", ofType: "plist")

//读取属性列表文件,并转化为可变字典对象
let data:NSMutableDictionary = NSMutableDictionary.init(contentsOfFile: plistPath!)!
        
//将字典对象转化为字符串对象
let message = data.description

print(message)

在程序沙箱目录中创建可持久化存储的plist文件

//创建一个沙箱目录下的路径
let path = NSHomeDirectory() + "/Documents/testPlist.plist"
if let dic:NSMutableDictionary = NSMutableDictionary.init(contentsOfFile: path) {
    let message = dic.description
    print(message)
} else {
    let filemanger = FileManager.default
    //  对写入的数据结构应属于以下几种如下: NSString NSData NSDate NSNumber NSArray NSDictionary
    let dictionary:NSDictionary = ["name":"chen chao", "age":"18", "info":"Good Teacher"]
    do {
        // 序列化,将数据转换成 XML 格式的文件
        let data = try PropertyListSerialization.data(fromPropertyList: dictionary, format: .xml , options: .zero)
        //创建文件
        filemanger.createFile(atPath: path, contents: data, attributes: nil)
    } catch {
        print("error")
    }
}

 

2017-10-10 20:51:13 bitcser 阅读数 2232

直接拖进工程的plist文件可能没有加入到Bundle Resource中,需要手动添加一下

swift 把数据写进plist文件中,有时候需要把后台返回的数据保存的时候,可以这么操作

let array = NSArray(objects: "hangge.com","baidu.com","google.com","163.com","qq.com")
let filePath:String = NSHomeDirectory() + "/Documents/webs.plist"
array.write(toFile: filePath, atomically: true)

swift获取模拟器沙盒document路径,这个方法可以找到的plist文件的路径,在Finder里前往-前往文件夹里可以进入
        let arr = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        debugPrint(arr[0])

oc方法

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
NSLog(@"%@", paths[0]);  


OC读取本地plist,这里写了一个方法

+(NSArray *)readPlistKey:(NSString *)string{
    NSString *path=[[NSBundle mainBundle]pathForResource:string ofType:@"plist"];
    NSArray *arr = [NSArray arrayWithContentsOfFile:path];
    return arr;
}
swift方法

let arr = NSArray(contentsOfFile: NSHomeDirectory() + "/Documents/webs.plist")



2018-12-20 13:59:09 wangai9140 阅读数 768

VC里面获取文件路径搭建界面

import UIKit

class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource{

    var tbv:UITableView?
    var nameArr:[String] = []
    
    var dict:NSDictionary = [:]
    var data:NSMutableDictionary = [:]
    
    var marr:NSMutableArray = []
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        // 生成文件的存储路径
        let plistPath = Bundle.main.path(forResource: "plist", ofType: "plist")
       // let plistPath = Bundle.main.path(forResource: "1", ofType: "plist")
        
        //读取属性列表文件,并转化为可变字典对象
        data = NSMutableDictionary(contentsOfFile: plistPath!)!
    
       // marr = NSMutableArray(contentsOfFile: plistPath!)!
       // print(marr)
        nameArr = data.allKeys as! [String]
        
        tbv = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
        view.addSubview(tbv!)
        
        tbv?.delegate = self
        tbv?.dataSource = self
        
        tbv?.register(UITableViewCell.self, forCellReuseIdentifier: "idCell")
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      //  return marr.count
        return nameArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "idCell")!
        cell.textLabel?.text = nameArr[indexPath.row];
//        let dic:NSDictionary = marr[indexPath.row] as! NSDictionary
//        let arr:NSArray = dic.allKeys as NSArray
//        cell.textLabel?.text = arr[0] as? String;
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if nameArr[indexPath.row]=="国外"{
            dict = data["国外"] as! NSDictionary
            let vc:SecondVC = SecondVC()
            
            vc.dict = dict
            
            self.navigationController?.pushViewController(vc, animated: true)
            
        }else{
            
            dict = data["国内"] as! NSDictionary
            
            let vc:ThreeVC = ThreeVC()
            
            vc.dict = dict
            
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
}

跳第二个界面

import UIKit

class SecondVC: UIViewController,UITableViewDelegate,UITableViewDataSource {

    var dict:NSDictionary = [:]
    var tbv:UITableView?
    
    var nameArr:[String] = []
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        view.backgroundColor = UIColor.white
        
        nameArr = dict.allKeys as! [String];
        
        tbv = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
        view.addSubview(tbv!)
        
        tbv?.delegate = self
        tbv?.dataSource = self
        
        tbv?.register(UITableViewCell.self, forCellReuseIdentifier: "idCell")
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return nameArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "idCell")!
        cell.textLabel?.text = nameArr[indexPath.row];
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if nameArr[indexPath.row]=="Britney Spears"{
            
            let arr:NSArray = dict["Britney Spears"] as! NSArray
            
            let vc:FourVC = FourVC()
            
            vc.dict = arr
            
            self.navigationController?.pushViewController(vc, animated: true)
            
        }else{
            let arr:NSArray = dict["Kelly Clarkson"] as! NSArray
            let vc:FourVC = FourVC()
            
            vc.dict = arr
            
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
    }

}

再跳到播放界面记得导入框架AVFoundation

import UIKit
import AVFoundation

class FourVC: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    var dict:NSArray = []
    var tbv:UITableView?
    var audioPlayer: AVAudioPlayer?
  //  var nameArr:[String] = []
    var select:Bool = true
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        // 设置音乐
        let path = Bundle.main.path(forResource: "试音碟-高山流水 (古筝)", ofType: "mp3")
        let pathURL=NSURL(fileURLWithPath: path!)
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: pathURL as URL)
        } catch {
            audioPlayer = nil
        }
        
        audioPlayer?.prepareToPlay()
        
        view.backgroundColor = UIColor.white
        
        tbv = UITableView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
        view.addSubview(tbv!)
        
        tbv?.delegate = self
        tbv?.dataSource = self
        
        tbv?.register(UITableViewCell.self, forCellReuseIdentifier: "idCell")
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dict.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "idCell")!
        cell.textLabel?.text = (dict[indexPath.row] as! String);
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if select==true {
            audioPlayer?.play()
            select = false
        }else{
            audioPlayer?.pause()
            select = true
        }
        
       // let audioPlayer = MusicViewController()
      //  audioPlayer.playMusic(filePath)
      //  self.navigationController!.pushViewController(audioPlayer, animated: true)
    }
}

swift plist文件

阅读数 446