ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်
`URLSession` က iOS ရဲ့ built-in networking API ပါ (Android ရဲ့ Retrofit လို third-party library မလိုအပ်ပါ — Apple ကိုယ်တိုင် ပေးထားပါတယ်)။ Modern Swift (5.5+) မှာ `async`/`await` syntax နဲ့ တွဲသုံးရင် callback-based code (`completion handler`) ထက် ဖတ်ရလွယ်ပါတယ် — `URLSession.shared.data(from: url)` က `async` function ပါ, `try await` နဲ့ ခေါ်ရပါတယ်။ JSON response ကို `Codable` protocol conform လုပ်ထားတဲ့ struct အဖြစ် `JSONDecoder` ကနေ decode လုပ်လို့ရပါတယ်.
လက်တွေ့ scenario နဲ့ ချိတ်ကြည့်မယ်
`struct WeatherResponse: Codable { let city: String; let tempCelsius: Double }` ကို define လုပ်ပြီး, `func fetchWeather(city: String) async throws -> WeatherResponse { let url = URL(string: "https://api.example.com/weather?city=\(city)")!; let (data, _) = try await URLSession.shared.data(from: url); return try JSONDecoder().decode(WeatherResponse.self, from: data) }` လို့ ရေးရင် — `Task { weather = try await fetchWeather(city: "Yangon") }` ခေါ်ရင် API ကနေ weather data ကို fetch ယူပြီး UI ထဲ ပြပေးနိုင်ပါတယ်.
အတူတူ ကြည့်မယ်
struct WeatherResponse: Codable {
let city: String
let tempCelsius: Double
}
func fetchWeather(city: String) async throws -> WeatherResponse {
let url = URL(string: "https://api.example.com/weather?city=\(city)")!
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(WeatherResponse.self, from: data)
}$ let weather = try await fetchWeather(city: "Yangon")
// weather: WeatherResponse(city: "Yangon", tempCelsius: 32.0)၅ မိနစ် စမ်းကြည့်
`fetchWeather` function ကို ကိုယ်တိုင် define လုပ်ကြည့်ပါ (public free weather API တစ်ခုကို ရွေးချယ်ပြီး) — `Task { }` ထဲက `try await` ခေါ်ပုံစံကို ဒီဇိုင်းရေးကြည့်ပါ။
သတိလေးတစ်ချက်
API key (secret) ကို app code ထဲ hardcode ရေးထားပြီး app bundle ထဲ ပါသွားရင်, decompile လုပ်ပြီး key ကို ထုတ်ယူနိုင်ပါတယ် — sensitive key ကို backend proxy server ကနေတစ်ဆင့် သုံးသင့်ပါတယ်။