Swift import local file import into SwiftyJSON

纵然是瞬间 提交于 2021-02-11 04:54:15

问题


I have to share the same data among 6 different apps so I thought a JSON file was the best way to save the data on each app.

I created a local file called "AppsInfo.json".

{
    "1": {
        "name": "app1",
        "desc": "",
        "amount": "19.99",
    },
    "2": {
        "name": "app2",
        "desc": "",
        "amount": "14.99",
        }
}

I can get the file path with this:

let filePath = Bundle.main.path(forResource: "AppsInfo", ofType: "json");

Now how do I load this file into something like SwiftyJSON?

Using Swift 4.2.

Thank you.


回答1:


First you read the Data from the path, better return URL of the resource

if let url = Bundle.main.url(forResource: "AppsInfo", withExtension: "json") {
    do {
        let data = try Data(contentsOf: url, options: .mappedIfSafe)
        let json = JSON(data: data)
    } catch {
        // handle error
    }
}


来源:https://stackoverflow.com/questions/55863489/swift-import-local-file-import-into-swiftyjson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!