본문 바로가기
SwiftUI

SwiftUI에서의 네트워킹 및 데이터 처리

by 안될개발 2025. 2. 5.

SwiftUI에서의 네트워킹 및 데이터 처리

SwiftUI에서의 네트워킹 및 데이터 처리

현대 앱에서는 서버와 데이터를 주고받는 기능이 필수적입니다. SwiftUI와 함께 네트워킹 작업을 수행하고 데이터를 처리하는 방법에 대해 알아보겠습니다.


1. URLSession을 이용한 네트워크 요청

URLSession은 네트워킹 작업을 수행하기 위해 Apple이 제공하는 기본 API입니다.

예제: 간단한 GET 요청

import SwiftUI

struct ContentView: View {
    @State private var joke: String = "Loading..."

    var body: some View {
        VStack {
            Text(joke)
                .padding()

            Button("Fetch Joke") {
                fetchJoke()
            }
        }
    }

    func fetchJoke() {
        guard let url = URL(string: "https://api.chucknorris.io/jokes/random") else { return }

        URLSession.shared.dataTask(with: url) { data, response, error in
            if let data = data, let jokeResponse = try? JSONDecoder().decode(Joke.self, from: data) {
                DispatchQueue.main.async {
                    joke = jokeResponse.value
                }
            }
        }.resume()
    }
}

struct Joke: Codable {
    let value: String
}

주요 포인트

  • URLSession.shared.dataTask는 비동기 요청을 수행합니다.
  • DispatchQueue.main.async를 사용하여 UI 업데이트를 메인 스레드에서 수행합니다.
  • JSONDecoder로 JSON 데이터를 디코딩합니다.

2. Combine을 이용한 네트워크 처리

Combine 프레임워크는 SwiftUI와 함께 반응형 프로그래밍을 가능하게 합니다.

예제: Combine을 활용한 네트워크 요청

import SwiftUI
import Combine

class JokeViewModel: ObservableObject {
    @Published var joke: String = "Loading..."
    private var cancellable: AnyCancellable?

    func fetchJoke() {
        guard let url = URL(string: "https://api.chucknorris.io/jokes/random") else { return }

        cancellable = URLSession.shared.dataTaskPublisher(for: url)
            .map { $0.data }
            .decode(type: Joke.self, decoder: JSONDecoder())
            .map { $0.value }
            .replaceError(with: "Error fetching joke")
            .receive(on: DispatchQueue.main)
            .assign(to: &$joke)
    }
}

struct ContentView: View {
    @StateObject private var viewModel = JokeViewModel()

    var body: some View {
        VStack {
            Text(viewModel.joke)
                .padding()

            Button("Fetch Joke") {
                viewModel.fetchJoke()
            }
        }
    }
}

주요 포인트

  • dataTaskPublisher를 사용해 네트워크 요청을 수행합니다.
  • map, decode, replaceError 등을 통해 데이터를 변환하고 에러를 처리합니다.
  • @Published와 @StateObject를 활용하여 UI 업데이트를 자동화합니다.

3. Codable을 이용한 JSON 데이터 디코딩

Codable 프로토콜은 JSON 데이터를 Swift 객체로 변환하는 데 사용됩니다.

예제: 중첩 JSON 디코딩

struct WeatherResponse: Codable {
    let main: Main

    struct Main: Codable {
        let temp: Double
    }
}

func parseWeatherData(_ data: Data) {
    if let weather = try? JSONDecoder().decode(WeatherResponse.self, from: data) {
        print("Temperature: \(weather.main.temp)")
    }
}

주요 포인트

  • 중첩된 JSON 구조도 손쉽게 디코딩할 수 있습니다.
  • try?를 사용하여 디코딩 오류를 안전하게 처리합니다.

4. 결론

SwiftUI에서 네트워킹과 데이터 처리는 URLSession, Combine, 그리고 Codable을 조합하여 강력하고 효율적인 방식으로 수행할 수 있습니다. 적절한 도구를 활용하여 데이터를 효율적으로 가져오고 처리하는 앱을 개발해 보시기 바랍니다.