首页 > 解决方案 > 我无法打开图像。解析不起作用

问题描述

我无法在“图片”中打开“网址”。解析不起作用。请帮忙。谢谢你。

"images": [
        {
          "url": "https://ktar.com/wp-content/uploads/2020/03/ap_27df5153e3bf48198ebcfd40900446d6.jpg",
          "width": 1280,
          "height": 853,
          "title": "Arizona reports 124 new coronavirus cases, five additional deaths",
          "attribution": null

==================================================== =====

==================================================== ===== API

{
      "path": "_news/2020-04-01-arizona-reports-124-new-coronavirus-cases-five-additional-deaths.md",
      "title": "Arizona reports 124 new coronavirus cases, five additional deaths",
      "excerpt": "The Arizona health department reported 124 new cases of coronavirus and five additional deaths on Wednesday morning, a day after the state's \"stay at home\" order went into effect.",
      "heat": 145,
      "tags": [
        "US"
      ],
      "type": "article",
      "webUrl": "https://ktar.com/story/3056413/arizona-reports-124-new-coronavirus-cases-five-additional-deaths/",
      "ampWebUrl": "https://ktar.com/story/3056413/arizona-reports-124-new-coronavirus-cases-five-additional-deaths/amp/",
      "cdnAmpWebUrl": "https://ktar-com.cdn.ampproject.org/c/s/ktar.com/story/3056413/arizona-reports-124-new-coronavirus-cases-five-additional-deaths/amp/",
      "publishedDateTime": "2020-04-01T09:09:00-07:00",
      "updatedDateTime": null,
      "provider": {
        "name": "KTAR News",
        "domain": "ktar.com",
        "images": null,
        "publishers": null,
        "authors": null
      },
      "images": [
        {
          "url": "https://ktar.com/wp-content/uploads/2020/03/ap_27df5153e3bf48198ebcfd40900446d6.jpg",
          "width": 1280,
          "height": 853,
          "title": "Arizona reports 124 new coronavirus cases, five additional deaths",
          "attribution": null
        }
      ],
      "locale": "en-us",
      "categories": [
        "news"
      ],
      "topics": [
        "Coronavirus in US",
        "Coronavirus",
        "New Cases"
      ]
    }

==================================================== ====

==================================================== ====

//  SPORTNEWSVC.swift
//  Hero

import Alamofire
import Kingfisher
import UIKit


class NewsVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    var news = [Article]()

    override func viewDidLoad() {
        super.viewDidLoad()

        getArticles()

    }

    func getArticles() {

        let parameters: Parameters = ["Subscription-Key": "3009d4ccc29e4808af1ccc25c69b4d5d"]

        Alamofire.request("https://api.smartable.ai/coronavirus/news/US", parameters: parameters).responseData { (response) in

            guard let data = response.data else { return }

            do {

//                let json = try JSONSerialization.jsonObject(with: data, options: [])
//                print(json)

                let topHeadlinesResponse = try JSONDecoder().decode(TopHeadlinesResponse.self, from: data)
                self.news = topHeadlinesResponse.news
                self.collectionView?.reloadData()

            } catch {
                print(error)
            }

        }

    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return news.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ArticleCell", for: indexPath) as? ArticleCell else { return UICollectionViewCell ()}

        let article = news[indexPath.item]
        cell.populate(with: article)

        return cell

    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        let height: CGFloat = 277

        let width = (collectionView.frame.width / 2) - 2

        let size = CGSize(width: width, height: height)

        return size

    }

}

==================================================== ====

==================================================== ====

//  Article.swift
//  Hero
//

import Foundation

struct Article: Decodable {
    let headline: String
    let url: String?

    private enum CodingKeys: String, CodingKey {
        case headline = "title"
        case url
    }

}

==================================================== ====

==================================================== ====

//
//  ArticleCell.swift
//  Hero

import UIKit
import Kingfisher

class ArticleCell: UICollectionViewCell {

    @IBOutlet weak var articleImageView: UIImageView!
    @IBOutlet weak var headlieLabel: UILabel!

    func populate(with article: Article){
        headlieLabel.text = article.headline

        if let url = article.url {
            let url = URL(string: url)
            articleImageView.kf.setImage(with: url)
        }

    }

}

==================================================== ====

==================================================== ====

import Foundation


struct TopHeadlinesResponse: Decodable {
    let news: [Article]
}

标签: jsonswiftxcode

解决方案


这个想法是您获得的 JSON 响应中的“图像”是一个数组,您需要在 Codable 结构中反映这一事实。解码魔法需要您遵循 JSON 数据结构和命名:因此,如果您在 'image' 字典中遇到字段 'width' - 您需要在 'image' 字段中有一个名为 'width' 的字段(例如,将图像作为单独的结构)

您可以在此处阅读有关 Decodables的更多信息

struct NewsApiResponse : Decodable {
    let status : String
    let updatedDateTime : Date?
    let news : [Article]
}

struct Article : Decodable {
    let id : Int
    let title : String
    let excerpt : String
    let webUrl : String
    let publishedDateTime : Date?
    let images : [Image]
}

struct Image : Decodable {
    let url : String
    let width : Int
    let height : Int
    let title : String
}

推荐阅读