mogeko6347
@mogeko6347

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

NewsAPI 文字化け

解決したいこと

SwiftUIとnewsAPIを使って記事を表示するアプリを作っていたところ、Almofireを利用したAPI通信は成功したのですが、下記のような文字化けが発生してしまいました...

発生している問題・エラー

Simulator Screen Shot - iPhone 14 Pro - 2022-11-24 at 20.46.09.png

該当のソースコード

import SwiftUI
import Alamofire


struct ContentView: View {
    @ObservedObject var store = Almo()
    var body: some View {
        //リスト表示(idはdescription(記事の内容)を使用)
        List(self.store.articles, id: \.description){ res in
            VStack(alignment: .leading){
                //              記事の表示
                Text(res.title ?? "")
                    .font(.title)
                Text(res.author ?? "")
                Text(res.description ?? "")
                Text(res.publishedAt ?? "")
                //          余白を開ける
                    .padding()
            }
        }
    }
}

struct NewsSource: Codable {
    let status: String?
    let totalResults: Int?
    var articles: [Article]
}

struct Article: Codable{
    var id: Int?
    var author: String?
    var title: String?
    var description: String?
    var publishedAt: String?
}

class Almo: ObservableObject {
    @Published var articles: [Article] = []
    func AFrequest()  {
        // AlamofireでAPIリクエストをする
        AF.request("キー付きのURL")
            .response { response in
                let decoder: JSONDecoder = JSONDecoder()
                do {
                    // decode関数の引数にはJSONからマッピングさせたいクラスをと実際のデータを指定する
                    let searchedResult = try decoder.decode(NewsSource.self, from: response.data!)
                    self.articles = searchedResult.articles
                    print(self.articles)
                    //実行時にコンソールに表示された内容
                    //
[JSON.Article(id: nil, author: nil, title: Optional("ドイツ戦勝利で祝日化提案も|ニフティニュース - ニフティニュース"), description: Optional("�@��t���D���s�̔���F�L�����N�^�[�u�ӂȂ����[�v��T�b�J�[���{��\\�������h�C�c��W�t1�����[�O����Ō��j�����������񂾁B�@������Ɂu���[�C�I����΂Ɂ[���ҁ[�ځ[�I�����[�I���{��\\���폟�����߂łƂ��c"), publishedAt: Optional("2022-11-24T10:30:00Z")), JSON.Article(id: nil, author: nil, title: ...

                    
                } catch {
                    // JSONの形式とクラスのプロパティが異なっている場合には失敗する
                    print("failed")
                    print(error.localizedDescription)
                }
            }
    }
    init(){
        AFrequest()
    }
}

勉強を始めたばかりで拙いコードで恐縮ですが、ご教授の方よろしくお願いいたします。

0

No Answers yet.

Your answer might help someone💌