LoginSignup
1
1

More than 3 years have passed since last update.

【Swift】NewsAPIで取得したjsonのデコードで失敗して半日潰した話

Posted at

前提

swiftの入門書を読んだだけの初学者がニュースアプリを作ってみたレベル。
ニュースはNewsAPIから取得。
取得したjsonは quicktype を使ってswiftのコードを生成した。
image.png

生成されたコード


// This file was generated from JSON Schema using quicktype, do not modify it directly.
// To parse the JSON, add this file to your project and do:
//
//   let welcome = try? newJSONDecoder().decode(Welcome.self, from: jsonData)

import Foundation

// MARK: - Welcome
struct Welcome: Codable {
    let status: String
    let totalResults: Int
    let articles: [Article]
}

// MARK: - Article
struct Article: Codable {
    let source: Source
    let author: String?
    let title, articleDescription: String
    let url: String
    let urlToImage: String
    let publishedAt: Date
    let content: String?

    enum CodingKeys: String, CodingKey {
        case source, author, title
        case articleDescription = "description"
        case url, urlToImage, publishedAt, content
    }
}

// MARK: - Source
struct Source: Codable {
    let id: String?
    let name: String
}

デコード処理に失敗した理由はデータ型のミスだった

設定の問題だったのか特にエラーも吐かず、なんで失敗しているのかわからなかったので、jsonとquicktype生成したコードをひたすらにらめっこしていたら、publishedAtの型が犯人だとわかった

json

// MARK: - Article
struct Article: Codable {
    〜略〜
  "publishedAt": "2020-12-07T14:30:00Z",
    〜略〜
}

生成コード

let publishedAt: Date

修正後

let publishedAt: String

上記の型を修正したら無事にデコードできた。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1