【问题标题】:Why can't I access my file despite it being in the ressources?为什么我无法访问我的文件,尽管它在资源中?
【发布时间】:2019-03-31 23:51:39
【问题描述】:

我正在尝试在 swift CLI 中打开一个 JSON 文件以对其进行解析。 但是,尽管文件在资源中,但我似乎无法生成正确的文件 URL。

if let path = Bundle.main.path(forResource: "test", ofType: "json") {
    do {
        let fileUrl = URL(fileURLWithPath: path)
        print(fileUrl)
        let data = try Data(contentsOf: fileUrl, options: .mappedIfSafe)
        print(data)
        let cities: [City] = try decoder.decode([City].self, from: data);
        return cities;
    } catch {
        return nil;
    }
}

如果我打开“构建阶段”菜单,我可以看到里面的 test.json 文件,但是当我构建时 swift 无法访问该文件。

提前感谢您的帮助。

【问题讨论】:

    标签: json swift xcode file


    【解决方案1】:

    试试下面的。

    import UIKit
    
    class ViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
    
            readData()
        }
    
        // MARK: - More
        func readData() {
            if let path = Bundle.main.path(forResource: "test", ofType: "json") {
                if let jsonData = readFileContent(path: path) {
                    do {
                        let result = try JSONDecoder().decode([City].self, from: jsonData)
                        print(result)
                    } catch let error as NSError {
                        print("\(error)")
                    }
                }
            }
        }
    
        func readFileContent(path: String) -> Data? {
            do {
                let url = URL(fileURLWithPath: path)
                let data = try Data(contentsOf: url)
                return data
            } catch let error as NSError {
                print("Error: \(error)")
            }
            return nil
        }
    }
    

    【讨论】:

    • 感谢您的回答。然而,我执行的问题是它似乎根本找不到文件“test.json”:它没有进入“if let path = ...”块。
    • 已经过测试。不要怪我。如果它不起作用,那肯定有你没有提到的东西。
    猜你喜欢
    • 1970-01-01
    • 2016-03-16
    • 2012-10-07
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 2012-02-17
    相关资源
    最近更新 更多