0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JSONを使用してHTTP通信

Posted at
import SwiftUI

struct ContentView: View {
    @State private var jsonData: [String: Any] = [:]

    var body: some View {
        VStack {
            Text("JSON Response:")
                .font(.headline)
                .padding()

            Text("\(jsonData)")
                .padding()

            Button("Fetch JSON") {
                fetchDataFromAPI()
            }
            .padding()
        }
    }

    func fetchDataFromAPI() {
        guard let url = URL(string: "https://example.com/api/data") else {
            return
        }

        URLSession.shared.dataTask(with: url) { (data, response, error) in
            if let error = error {
                print("Error: \(error)")
                return
            }

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

            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                if let jsonDictionary = json as? [String: Any] {
                    DispatchQueue.main.async {
                        self.jsonData = jsonDictionary
                    }
                }
            } catch {
                print("JSON parsing error: \(error)")
            }
        }.resume()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?