Swift 4 iOS Parse JSON to Collection View



我有一个小问题。我只知道如何将JSON Image墨水解析为收集单元,如果JSON作为"键":" value",但是这次我在下面的链接上获得了JSON的类型...

问题是...我在数组["链接","链接"," link"]上有倍数链接。我如何将第一个数组中的3-4张图像放在一个集合视图中(下面的屏幕截图(,然后填充其他单元格

结构是..一个tableview->在表视图的每个单元格上,我将CollectionView->收集带有带有水平滚动和标题的图像块的单元格

下面的屏幕截图:

https://d.radikal.ru/d30/1803/60/35717754afbd.png

{ "list": [
{
    "title" : "iPhone 5s",
    "images": [
        "https://upload.wikimedia.org/wikipedia/commons/f/fd/IPhone_5S.jpg",
        "http://img01.ibnlive.in/ibnlive/uploads/2015/12/apple-iphone5s-151215.jpg",
        "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR5cv-olMz3XKQNhQP4SpwiwqtiDreaBlpESHdCDc6Jm5GjHzRsHcxXrqAI"
    ]
},
{
    "title" : "iPhone 6s",
    "images": [
        "https://c1.staticflickr.com/2/1665/26162561181_01148e99ee_b.jpg",
        "https://img1.ibay.com.mv/is1/full/2017/11/item_2028958_545.jpg",
        "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSz8jIpCOU94HxZEab_vJdl9nGsaAOO18dqq2BXt_L2-PnWhroi",
        "https://c1.staticflickr.com/4/3907/15102682838_25e6c90469_b.jpg",
        "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTnMHHcDnMlsrtPpZmfLjQqlJXQNNEvTTg7WWMGcbOHOvxdVUoi"
    ]
},
{
    "title" : "iPhone 7",
    "images": [
        "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRQYu7fKAuYLwQCiilRNCv_wzVZbOpLGsrRzQA7prdgToCiBzsQ",
        "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSGS8lca49LZGvPUtJxrof6DuzvjgKiR_0Nei_b8zeR-3uq1kzyLQ",
        "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSGS8lca49LZGvPUtJxrof6DuzvjgKiR_0Nei_b8zeR-3uq1kzyLQ",
        "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTko9xdQRKcdJrshSPWCjTtml9eSKiABSN--VhC5YV8MMASVRfgYw",
        "https://cdn.pixabay.com/photo/2014/12/10/12/27/iphone-563070_960_720.jpg"
    ]
}
]
}

用链接加载照片的扩展

extension UIImageView{
func downloadImg(from url: String){
let urlRequest = URLRequest(url: URL(string: url)!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
    if error != nil{
        print(error)
        return
    }
    DispatchQueue.main.async {
        self.image = UIImage(data: data!)
    }
}
task.resume()
}
}

我的对象结构

struct info : Decodable {
let list : [lists]
}
struct lists : Decodable{
let title : String?
let images : [String]?
}

通常,如果JSON具有类似结构的"键":" value",我会这样做。

cell.productImage.downloadImg(from: (arrayImg?[indexPath.row].url)!)

首先,请符合结构名称以大写字母开头的命名约定。

您可以将URL字符串直接解码到URL,并且如果JSON包含所有键

,则不会将属性声明为选项
struct Info : Decodable {
    let list : [List]
}
struct List : Decodable {
    let title : String
    let images : [URL]
}

在数组上解码JSON并迭代(data是接收到的Data实例(

do {
    let result = try JSONDecoder().decode(Info.self, from: data)
    for phone in result.list {
        for imageURL in phone.images {
          print(imageURL)
        }
    }
} catch { print(error) }

最新更新