2017-02-10 239 views
0

块内比方说,我在下面的方式构造JSON数据:访问URL和阵列从JSON数据

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

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

+0

JSON是很容易阅读:'{}'代表diictionary,'[]'数组,在双引号的文字是'String',一个包含一个点的数字是'Double',没有点是'Int','true'或'false'是'Bool','''NSNull'.有几百个相关的问题如何解析JSON在Stackoverflow上。 – vadian

回答

2

对于数组来说,它非常简单。无论你有你的功能listenes的火力点变化,我会假设你有存储在一个变量一样let apple

然后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 

对于图像,这里有几个选项。第一个(和坏的)是synchrounsly获取网址的数据,并将其设置为的形象图如下所示:

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!) 

这种方法的事情是,它是NOT OK。它会在发出请求并下载图像时阻塞主线程,导致应用程序无响应。

更好的方法将是异步取回它。有几个库真的有帮助,如AlamofireImage,但它可以用准系统基础很容易完成。要做到这一点,你应该使用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()