SDKs

Swift

iOS와 macOS 앱을 위한 Swift의 관용적인 패턴

내장 URLSession + Codable 을 사용하세요. 전반적으로 async/await. iOS 15+, macOS 12+ 를 대상으로 합니다.

설정

import Foundation

let api = URL(string: "https://openapi.thunderbit.com/openapi/v1")!
let apiKey = ProcessInfo.processInfo.environment["THUNDERBIT_API_KEY"]!

func request(path: String, body: Data? = nil) -> URLRequest {
    var req = URLRequest(url: api.appendingPathComponent(path))
    req.httpMethod = body == nil ? "GET" : "POST"
    req.httpBody = body
    req.timeoutInterval = 60
    req.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
    req.setValue("application/json", forHTTPHeaderField: "Content-Type")
    return req
}

페이지 Distill

struct DistillBody: Encodable { let url: String }
struct DistillResponse: Decodable {
    struct Data: Decodable { let markdown: String }
    let data: Data
}

let body = try JSONEncoder().encode(DistillBody(url: "https://thunderbit.com/playground"))
let (data, _) = try await URLSession.shared.data(for: request(path: "distill", body: body))
let result = try JSONDecoder().decode(DistillResponse.self, from: data)
print(result.data.markdown)

구조화된 데이터 Extract

struct Product: Decodable { let name: String; let price: Double }
struct ExtractResponse: Decodable { let data: Product }

let payload: [String: Any] = [
    "url": "https://example.com/product/iphone-15-pro",
    "schema": [
        "type": "object",
        "properties": [
            "name":  ["type": "string"],
            "price": ["type": "number"]
        ],
        "required": ["name", "price"]
    ]
]
let body = try JSONSerialization.data(withJSONObject: payload)
let (data, _) = try await URLSession.shared.data(for: request(path: "extract", body: body))
let product = try JSONDecoder().decode(ExtractResponse.self, from: data).data

Batch + Webhook

제출 후 서버 측 Webhook 핸들러가 무거운 작업을 처리하도록 하세요 —— 대부분의 iOS 앱은 폴링하지 않는 것이 좋습니다. Webhooks 를 참고하세요.

공식 Swift SDK 가 개발 중입니다 —— 곧 다시 확인해 주세요.