2017-02-10 143 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()