LoginSignup
1
7

More than 1 year has passed since last update.

コピペで動く、SwiftUIでapiからデータを取得して表示する方法

Last updated at Posted at 2023-03-01

まずは外部APIからコメントデータを取得するために、URLSession を使用してAPIにリクエストを送信する必要があります。以下は、SwiftUIでURLSessionを使用して、外部APIからコメントデータを取得するための簡単な方法です。


import SwiftUI

struct Comment: Codable {
    var id: Int
    var name: String
    var email: String
    var body: String
}

class CommentLoader: ObservableObject {
    @Published var comments = [Comment]()

    init() {
        guard let url = URL(string: "https://jsonplaceholder.typicode.com/comments") else {
            print("Invalid URL")
            return
        }
        
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            if let error = error {
                print("Error: \(error.localizedDescription)")
                return
            }

            guard let data = data else {
                print("Invalid data")
                return
            }

            do {
                let decoder = JSONDecoder()
                let comments = try decoder.decode([Comment].self, from: data)
                DispatchQueue.main.async {
                    self.comments = comments
                }
            } catch let error {
                print("Error decoding JSON: \(error.localizedDescription)")
            }
        }.resume()
    }
}

struct ContentView: View {
    @ObservedObject var commentLoader = CommentLoader()

    var body: some View {
        List(commentLoader.comments, id: \.id) { comment in
            VStack(alignment: .leading, spacing: 8) {
                Text(comment.name)
                    .font(.headline)
                Text(comment.body)
                    .font(.subheadline)
                Text(comment.email)
                    .font(.subheadline)
                    .foregroundColor(.gray)
            }
        }
    }
}

上記のコードは、 CommentというCodableな構造体を定義し、 CommentLoaderというObservableObjectを作成し、 ContentViewでCommentLoaderをインスタンス化し、 Listを使用して、コメントデータを表示しています。 CommentLoaderのinitメソッドでは、 URLSessionを使用して、APIからコメントデータを取得し、 JSONDecoderを使用してJSONを解析しています。 解析されたコメントデータは、 @Publishedを使用してCommentLoader内の commentsプロパティに公開され、 ContentViewに自動的に通知され、更新されます。

APIを使って他のサイトからデータを取得することができるよ。取得したデータをSwiftUIで使って表示することもできるんだよ〜。

データの取得には、URLセッションを使ってAPIリクエストを送信する必要があるんだ。リクエストが成功したら、レスポンスを解析して必要なデータを取り出し、SwiftUIで表示できるようにするんだ。

APIリクエストを送信するには、URLを指定する必要があるよ〜。URLは文字列で表現され、URL(string:)を使ってURLオブジェクトを作ることができるよ〜。

データを取得したら、SwiftUIで表示するために、取得したデータを解析して必要な情報を取り出す必要があるよ。JSONデータを取得した場合、SwiftにはJSONDecoderという便利なツールがあるので、それを使ってJSONを解析するといいよ〜。

解析したデータを、SwiftUIで表示するためには、ListやForEachを使って表示することができるよ〜。データが多い場合は、スクロール可能なリストを作ることもできるんだ〜。

まあ、あくまでも例外はあるけど、基本的にAPIを使って外部データを取得してSwiftUIで表示することは簡単だよ〜。ネット上にたくさんのAPIがあるから、興味があったらいろいろと試してみるといいよ〜。

1
7
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
7