
Let’s go through each step with Swift code:
- Get OpenWeatherMap API Key:
- Go to the OpenWeatherMap website and sign up for an account to get your API key.
- Create a New Xcode Project:
- Open Xcode and create a new iOS project with a Single View App template.
- UI Design:
- Open the Main.storyboard file and design your user interface.
- Add a label for displaying weather information and a text field for entering the location.
- Add a button for fetching weather data and connect it to an IBAction in your view controller.
- Networking:
- Create a new Swift file named WeatherAPI.swift.
import Foundation
struct WeatherAPI {
static let apiKey = "YOUR_API_KEY"
static let baseURL = "http://api.openweathermap.org/data/2.5/weather"
static func fetchWeatherData(for city: String, completion: @escaping (Result<WeatherData, Error>) -> Void) {
let urlString = "\(baseURL)?q=\(city)&appid=\(apiKey)"
guard let url = URL(string: urlString) else {
completion(.failure(NSError(domain: "Invalid URL", code: 0, userInfo: nil)))
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
completion(.failure(error))
return
}
guard let data = data else {
completion(.failure(NSError(domain: "No data received", code: 0, userInfo: nil)))
return
}
do {
let weatherData = try JSONDecoder().decode(WeatherData.self, from: data)
completion(.success(weatherData))
} catch {
completion(.failure(error))
}
}.resume()
}
}
- Define Data Model:
- Create a new Swift file named WeatherData.swift.
import Foundation
struct WeatherData: Codable {
let main: Main
let weather: [Weather]
}
struct Main: Codable {
let temp: Double
}
struct Weather: Codable {
let description: String
}
- Update UI:
- Open ViewController.swift and implement the IBAction for the fetch weather button.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet weak var weatherLabel: UILabel!
@IBAction func fetchWeatherButtonTapped(_ sender: UIButton) {
guard let city = locationTextField.text else { return }
WeatherAPI.fetchWeatherData(for: city) { result in
switch result {
case .success(let weatherData):
let temperature = String(format: "%.1f", weatherData.main.temp - 273.15)
let description = weatherData.weather.first?.description ?? ""
DispatchQueue.main.async {
self.weatherLabel.text = "Temperature: \(temperature)°C, Description: \(description)"
}
case .failure(let error):
DispatchQueue.main.async {
self.weatherLabel.text = "Error: \(error.localizedDescription)"
}
}
}
}
}
- Error Handling:
- The error handling is done within the fetchWeatherData method of WeatherAPI.swift.
- Testing:
- Run your app in the simulator or on a device and test it with different locations.
- User Experience Enhancements:
- You can add additional features like automatic location detection using Core Location or unit conversion.
- Deployment:
- Once your app is ready, you can deploy it to the App Store or distribute it to testers.
This code fetches weather data for a given city using the OpenWeatherMap API and displays the temperature and weather description in the UI. Make sure to replace “YOUR_API_KEY” with your actual OpenWeatherMap API key.