【问题标题】:Accessing URL and Array from within a Block of JSON Data从 JSON 数据块中访问 URL 和数组
【发布时间】:2017-02-10 17:30:57
【问题描述】:

假设我的 JSON 数据结构如下:

{ "fruits" : {
    "apple": {
        "name": "Gala"
        "color": "red",
        "picture": "//juliandance.org/wp-content/uploads/2016/01/RedApple.jpg",
        "noOfFruit": [1, 2]
    }
}

如何使用 iOS 版本的 Firebase 访问图片和 noOfFruit 数组?我想用一个单元格制作一个表格视图,其中列出了苹果的名称、颜色、苹果的图片,然后列出了水果的数量。我知道如何获取“颜色”和“名称”值,但是如何访问数组并将其转换为字符串和图像,以便在表格视图中显示图像?任何帮助表示赞赏!

【问题讨论】:

  • JSON 很容易阅读:{} 表示字典,[] 数组,双引号中的文本为String,包含点的数字为Double,不带点为InttruefalseBool<null>NSNull。在 Stackoverflow 上有数百个相关问题如何解析 JSON。

标签: ios json swift firebase firebase-realtime-database


【解决方案1】:

对于数组,真的很简单。无论您的函数在哪里侦听 Firebase 更改,我都会想象您将 apple 键下的信息存储在 let apple 之类的变量中

然后,您可以将 noOfFruit 的值转换为数组,如下所示:

let apple = // what you had before
guard let noOfFruit = apple["noOfFruit"] as? [Int] else {
    return
}

//Here you have the array of ints called noOfFruit

对于图像,有几个选项。第一个(也是不好的)是同步获取 url 的数据并将其设置为图像视图,如下所示:

let url = URL(string: picture)
let data = try? Data(contentsOf: url!) //this may break due to force unwrapping, make sure it exists
imageView.image = UIImage(data: data!)

这种方法的问题是它不行。它将在发出请求和下载图像时阻塞主线程,使应用程序无响应。

更好的 方法是异步获取它。有几个库确实有帮助,例如 AlamofireImage,但可以通过准系统 Foundation 轻松完成。为此,您应该使用 URLSession 类,如下所示:

guard let url = URL(string: picture) else { 
    return 
}

URLSession.shared.dataTask(with: url) { data, response, error in
    if let error = error {
        print(error)
        return
    }

    //Remember to do UI updates in the main thread
    DispatchQueue.main.async {
        self.myImageView.image = UIImage(data: data!)
    }
}.resume()

【讨论】:

    猜你喜欢
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    • 2019-05-24
    • 2016-09-12
    相关资源
    最近更新 更多