代码之家  ›  专栏  ›  技术社区  ›  Jo Momma

当我试图通过Bundle访问plist时,它返回nil。梅因,但我知道它在那里

  •  0
  • Jo Momma  · 技术社区  · 5 年前

    我创造了一个。plist文件名为 Configuration.plist 密码。运行一次应用程序后,我可以在文件系统(使用模拟器)中看到它确实存在。

    enter image description here 我

    我正在学习iOS开发。在互联网上搜索“如何从我自己的plist中阅读”的答案后,我不断看到一些教程,它们告诉我这样阅读这个文件:

    if let path = Bundle.main.path(forResource: K.files.config, ofType: "plist"),
               let xml = FileManager.default.contents(atPath: path),
               let config = try? PropertyListDecoder().decode(Configuration.self, from: xml){
    
                print("We have a config: \(config.mainTitle)")
                return config
            } else {
                print("No config ☹️")
                return nil
            }
    

    在上面的例子中,K.files。config只是一个字符串常量,配置类符合可编码协议。K.file的值。配置是“配置”。然而,在上面的例子中,path总是返回nil。但我知道这个文件存在!!

    事实上,当我像这样访问这个文件时,我实际上可以得到路径:

    let fileName = K.files.config + ".plist"
            var filePath = ""
            
            let dirs: [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)
            
            if dirs.count > 0 {
                let dir = dirs[0]
                filePath = dir.appendingFormat("/" + fileName)
                print("Local path: \(filePath)")
            } else {
                print("Could not find local directory for Configuration.plist")
                return nil
            }
            
            if let xml = FileManager.default.contents(atPath: filePath),
               let config = try? PropertyListDecoder().decode(Configuration.self, from: xml){
                print("got a config: \(config.mainTitle)")
            } else {
                print("didn't get the xml")
            }
    

    这是更加冗长和丑陋的。为什么第一种方法不起作用?

    0 回复  |  直到 5 年前
        1
  •  1
  •   DonMag    5 年前

    当你创造 Configuration.plist 您正在将其保存到“文档”文件夹中。。。

    那个文件夹是 外部 你的应用程序包。

    所以,在第一个代码块中,您试图加载它 从包裹里 ,但失败了。

    第二个代码块正确地从Documents文件夹中查找并加载文件。