[swift] 스위프트 아폴로를 사용한 채팅 앱 구현 방법

소개

스위프트 언어를 기반으로 한 아폴로(Apollo)라이브러리는 GraphQL을 쉽게 활용할 수 있도록 도와주는 도구입니다. 이 문서에서는 스위프트 아폴로를 사용하여 채팅 앱을 구현하는 방법을 알아보겠습니다.

선행 작업

아래와 같은 선행 작업을 수행해야 합니다:

프로젝트 설정

  1. Xcode에서 프로젝트를 생성합니다.
  2. 프로젝트의 루트 디렉토리에서 터미널을 열고 pod init을 실행하여 Podfile을 생성합니다.
  3. Podfile을 열고 다음과 같이 아폴로 의존성을 추가합니다:
    target 'YourProjectName' do
      # 기존에 있는 의존성은 제외하고 추가합니다
      pod 'Apollo-ios', '~> 0.35.0'
    end
    
  4. 터미널에서 pod install을 실행하여 아폴로 라이브러리를 설치합니다.

아폴로 설정

  1. Xcode에서 ‘YourProjectName.xcworkspace’ 파일을 엽니다.
  2. 프로젝트의 루트 디렉토리에서 YourProjectName.xcodeproj 파일을 삭제합니다. (중복으로 생성되지 않도록 합니다)
  3. Xcode에서 Build Phases로 이동합니다.
  4. New Run Script Phase를 추가하고, 다음 스크립트를 입력합니다:
    if which swiftlint >/dev/null; then
      swiftlint
    else
      echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"
    fi
    
  5. Xcode를 종료하고 터미널에서 다음 명령을 실행하여 프로젝트를 업데이트합니다:
    Pods/Target Support Files/Pods-YourProjectName/Pods-YourProjectName-frameworks.sh
    

채팅 앱 구현

  1. GraphQL 스키마를 작성합니다. 이 스키마는 백엔드 서버에 대한 API 정의입니다.
  2. Xcode에서 .graphql 파일을 프로젝트에 추가합니다. 이 파일에는 GraphQL 쿼리와 뮤테이션 정의가 포함됩니다.
  3. 아폴로 클라이언트를 생성하고 초기화합니다. ExampleChatClient.swift 파일을 생성하고 다음 코드를 입력합니다: ```swift import Foundation import Apollo

class ExampleChatClient { static let shared = ExampleChatClient()

private(set) lazy var apollo: ApolloClient = { let url = URL(string: “https://example.com/graphql”)! let configuration = URLSessionConfiguration.default let token = “your-auth-token” configuration.httpAdditionalHeaders = [“Authorization”: “Bearer (token)”] let transport = HTTPNetworkTransport(url: url, configuration: configuration) return ApolloClient(networkTransport: transport) }() }

4. 채팅 앱의 중심이 되는 뷰 컨트롤러를 생성합니다. ExampleChatViewController.swift 파일을 생성하고 다음 코드를 입력합니다:
```swift
import UIKit
import Apollo

class ExampleChatViewController: UIViewController {
  // ...
  private var messages: [Message] = []

  // ...

  func fetchMessages() {
    let query = GetMessagesQuery()
    ExampleChatClient.shared.apollo.fetch(query: query) { result in
      switch result {
      case .success(let graphQLResult):
        if let messages = graphQLResult.data?.messages {
          self.messages = messages
          self.tableView.reloadData()
        }
      case .failure(let error):
        print("Failed to fetch messages: \(error)")
      }
    }
  }

  // ...
}
  1. 채팅 메시지를 보내는 뮤테이션을 작성합니다. ExampleChatViewController.swift 파일에 다음 코드를 추가합니다:
    func sendMessage(text: String) {
      let mutation = SendMessageMutation(text: text)
      ExampleChatClient.shared.apollo.perform(mutation: mutation) { result in
     switch result {
     case .success:
       self.fetchMessages() // 메시지 전송 후 메시지 목록을 업데이트합니다.
     case .failure(let error):
       print("Failed to send message: \(error)")
     }
      }
    }
    
  2. 채팅 앱의 UI를 구현합니다. 예를 들어, 테이블 뷰를 사용하여 메시지 목록을 표시하고, 텍스트 필드와 버튼을 추가하여 메시지를 입력하고 전송할 수 있도록 합니다.

이제 스위프트 아폴로를 사용하여 채팅 앱을 구현하는 방법을 알아보았습니다. 추가 작업으로 채팅 메시지 업데이트 등의 기능을 추가할 수 있습니다. 아폴로의 공식 문서 및 예제를 참고하여 더 많은 기능을 익힐 수도 있습니다.

참고자료