Popular Searches
Popular Course Categories
Popular Courses

Developing a Weather App Using REST API Integration

Developing a Weather App Using REST API Integration

Real-World iOS Application Projects

Developing a Weather App Using REST API Integration

Course: iOS App Development

Topic: Developing a Weather App Using REST API Integration

Course Link: iOS App Development Training

Demo Link: Register for Free Course Demo

Website: JustAcademy


1. Introduction to Weather App Development

A Weather App is a mobile application that displays real-time weather information and forecasts for a selected city or the user's current location. It retrieves weather information from external weather services through REST APIs and presents the data using an attractive and user-friendly interface.

Developing a weather application in iOS helps developers understand important concepts such as API integration, HTTP requests, JSON parsing, asynchronous programming, Core Location, SwiftUI, and error handling.

In iOS development, Swift and URLSession are commonly used to communicate with REST APIs. The received JSON response is decoded into Swift model structures and displayed in the application.

Key Features of a Weather App

  • Display current temperature and weather conditions.
  • Show humidity, wind speed, and atmospheric pressure.
  • Retrieve weather information using city names.
  • Detect the user's current location using Core Location.
  • Display hourly and daily weather forecasts.
  • Show weather icons based on current conditions.
  • Handle API errors and network connectivity issues.
  • Provide a clean and responsive user interface.

2. Understanding REST API Integration

REST stands for Representational State Transfer. It is an architectural approach used for communication between applications over HTTP. A weather application sends requests to a weather service and receives weather information in JSON format.

How REST API Integration Works

  1. The user opens the weather application.
  2. The application collects a city name or current location coordinates.
  3. The application constructs an API request URL.
  4. URLSession sends an HTTP request to the weather service.
  5. The server processes the request and returns a JSON response.
  6. The application decodes the JSON data into Swift objects.
  7. The weather information is displayed on the screen.

Example of a Weather API Request

https://api.openweathermap.org/data/2.5/weather?q=Mumbai&appid=YOUR_API_KEY&units=metric

In this example:

  • q=Mumbai: Specifies the city for which weather information is requested.
  • appid: Represents the API authentication key.
  • units=metric: Requests temperature in Celsius.
  • API response: Contains temperature, humidity, weather conditions, and other information.

3. Selecting a Weather API Provider

Before developing the application, developers need to select a weather API provider. Several services provide current weather information and forecast data.

API Provider Features Common Usage
OpenWeather Current weather, forecasts, weather conditions Weather applications
WeatherAPI Current weather, hourly and daily forecasts Location-based weather apps
Tomorrow.io Weather forecasts and environmental information Advanced weather applications
Apple WeatherKit Weather information through Apple's weather services Native iOS weather applications

Steps to Obtain an API Key

  1. Visit the selected weather API provider's official website.
  2. Create an account or sign in.
  3. Open the developer dashboard.
  4. Generate or obtain an API key.
  5. Review the API documentation and request limits.
  6. Store the API key securely in the application configuration.

Important: Never publish private API keys in a public GitHub repository. For production applications, sensitive API credentials should be protected using a secure backend or another appropriate credential-management approach.

4. Setting Up the iOS Weather App Project

The first step is to create a new iOS project using Xcode. SwiftUI can be used to design the interface, while URLSession handles API communication.

Project Creation Steps

  1. Open Xcode on your Mac.
  2. Select Create a New Project.
  3. Choose the iOS App template.
  4. Enter the project name as WeatherApp.
  5. Select Swift as the programming language.
  6. Select SwiftUI as the interface.
  7. Choose the required deployment target.
  8. Click Create to generate the project.

Suggested Project Structure

WeatherApp/
│
├── Models/
│   └── WeatherModel.swift
│
├── Services/
│   └── WeatherService.swift
│
├── ViewModels/
│   └── WeatherViewModel.swift
│
├── Views/
│   ├── ContentView.swift
│   ├── WeatherDetailsView.swift
│   └── ForecastView.swift
│
├── Assets.xcassets/
│
└── WeatherApp.swift

This structure separates API communication, data models, application logic, and user interface components. It makes the application easier to maintain and extend.

5. Understanding URLSession in iOS

URLSession is a built-in Apple framework used to perform network requests. It allows an iOS application to communicate with web services using HTTP and HTTPS protocols.

Main Responsibilities of URLSession

  • Sending HTTP requests to remote servers.
  • Downloading information from APIs.
  • Uploading data to web services.
  • Managing network responses.
  • Handling asynchronous network operations.

Example: Importing Foundation

import Foundation

The Foundation framework provides URL, URLRequest, URLSession, JSONDecoder, and other networking utilities required for REST API integration.

6. Creating Weather Data Models Using Codable

Weather APIs generally return information in JSON format. Swift uses the Codable protocol to convert JSON data into strongly typed Swift structures.

Example JSON Response

{
  "name": "Mumbai",
  "main": {
    "temp": 29.5,
    "humidity": 72,
    "pressure": 1008
  },
  "weather": [
    {
      "description": "scattered clouds",
      "icon": "03d"
    }
  ],
  "wind": {
    "speed": 4.2
  }
}

Creating WeatherModel.swift

import Foundation

struct WeatherResponse: Codable {
    let name: String
    let main: MainWeather
    let weather: [WeatherCondition]
    let wind: Wind
}

struct MainWeather: Codable {
    let temp: Double
    let humidity: Int
    let pressure: Int
}

struct WeatherCondition: Codable {
    let description: String
    let icon: String
}

struct Wind: Codable {
    let speed: Double
}

Explanation

  • WeatherResponse: Represents the complete API response.
  • MainWeather: Stores temperature, humidity, and pressure.
  • WeatherCondition: Stores the weather description and icon identifier.
  • Wind: Stores wind speed.
  • Codable: Enables encoding and decoding between Swift types and JSON.

7. Creating the Weather API Service

The API service manages communication between the iOS application and the weather server. Keeping API logic in a separate service class prevents networking code from being mixed with the user interface.

WeatherService.swift

import Foundation

enum WeatherError: Error {
    case invalidURL
    case invalidResponse
}

class WeatherService {

    private let apiKey = "YOUR_API_KEY"

    func fetchWeather(city: String) async throws
        -> WeatherResponse {

        var components = URLComponents(
            string: "https://api.openweathermap.org/data/2.5/weather"
        )

        components?.queryItems = [
            URLQueryItem(name: "q", value: city),
            URLQueryItem(name: "appid", value: apiKey),
            URLQueryItem(name: "units", value: "metric")
        ]

        guard let url = components?.url else {
            throw WeatherError.invalidURL
        }

        let (data, response) = try await URLSession.shared.data(
            from: url
        )

        guard let httpResponse = response as? HTTPURLResponse,
              (200...299).contains(httpResponse.statusCode) else {
            throw WeatherError.invalidResponse
        }

        let weather = try JSONDecoder().decode(
            WeatherResponse.self,
            from: data
        )

        return weather
    }
}

Understanding the Code

  1. WeatherService: Defines a separate class for API operations.
  2. apiKey: Stores the weather service credential for development purposes.
  3. URLComponents: Constructs the request URL and query parameters safely.
  4. URLSession.shared.data: Sends the request and receives the response data.
  5. HTTPURLResponse: Checks the HTTP status code.
  6. JSONDecoder: Converts JSON data into WeatherResponse.
  7. return weather: Returns the decoded weather information.

8. Implementing Asynchronous API Calls

Weather information is retrieved from remote servers, so API requests may take some time. Asynchronous programming allows the application to perform network operations without blocking the main user interface.

Understanding async and await

  • async: Declares a function that performs asynchronous operations.
  • await: Waits for an asynchronous operation to complete.
  • throws: Allows a function to report errors.
  • do-catch: Handles errors generated during asynchronous operations.

Example

func loadWeather() async {
    do {
        let weather = try await WeatherService()
            .fetchWeather(city: "Mumbai")

        print("City: \(weather.name)")
        print("Temperature: \(weather.main.temp)")

    } catch {
        print("Unable to fetch weather: \(error)")
    }
}

Asynchronous operations are particularly useful when retrieving weather information, searching for cities, refreshing forecasts, and loading weather icons.

9. Creating the Weather ViewModel

The ViewModel manages application data and connects the API service with the SwiftUI interface. It follows the Model-View-ViewModel (MVVM) architecture.

WeatherViewModel.swift

import Foundation
import SwiftUI

@MainActor
class WeatherViewModel: ObservableObject {

    @Published var weather: WeatherResponse?
    @Published var isLoading = false
    @Published var errorMessage: String?

    private let service = WeatherService()

    func fetchWeather(city: String) async {

        isLoading = true
        errorMessage = nil

        defer {
            isLoading = false
        }

        do {
            weather = try await service.fetchWeather(
                city: city
            )
        } catch {
            errorMessage = "Unable to load weather data."
        }
    }
}

Explanation of Important Properties

  • @MainActor: Ensures UI-related state updates occur on the main actor.
  • @Published: Notifies the interface when observable properties change.
  • weather: Stores the latest weather response.
  • isLoading: Indicates whether an API request is in progress.
  • errorMessage: Stores an error message for display.
  • defer: Ensures the loading state is reset when the operation finishes.

10. Designing the Weather App Interface Using SwiftUI

SwiftUI provides declarative UI components that make it easier to build modern iOS applications. The weather screen should present important information clearly and allow users to search for different cities.

Important SwiftUI Components

Component Purpose
VStack Arranges components vertically.
HStack Arranges components horizontally.
Text Displays city names, temperature, and weather descriptions.
Image Displays weather icons and visual elements.
TextField Allows users to enter a city name.
Button Triggers weather searches.
ProgressView Displays a loading indicator.
ScrollView Displays additional weather information.

Example: ContentView.swift

import SwiftUI

struct ContentView: View {

    @StateObject private var viewModel = WeatherViewModel()
    @State private var city = "Mumbai"

    var body: some View {

        NavigationStack {
            VStack(spacing: 20) {

                TextField("Enter city name", text: $city)
                    .textFieldStyle(.roundedBorder)
                    .padding(.horizontal)

                Button("Search Weather") {
                    Task {
                        await viewModel.fetchWeather(
                            city: city
                        )
                    }
                }
                .buttonStyle(.borderedProminent)

                if viewModel.isLoading {
                    ProgressView("Loading weather...")
                }

                if let weather = viewModel.weather {

                    Text(weather.name)
                        .font(.largeTitle)
                        .bold()

                    Text(
                        "\(weather.main.temp, specifier: "%.1f") °C"
                    )
                    .font(.system(size: 48))
                    .bold()

                    Text(
                        weather.weather.first?.description
                        ?? "Weather information unavailable"
                    )

                    HStack {
                        Text(
                            "Humidity: \(weather.main.humidity)%"
                        )

                        Text(
                            "Wind: \(weather.wind.speed) m/s"
                        )
                    }
                }

                if let error = viewModel.errorMessage {
                    Text(error)
                        .foregroundStyle(.red)
                }

                Spacer()
            }
            .padding()
            .navigationTitle("Weather App")
            .task {
                await viewModel.fetchWeather(city: city)
            }
        }
    }
}

Interface Features

  • City search field for entering location names.
  • Search button for retrieving weather information.
  • Large temperature display for better visibility.
  • Weather description for current conditions.
  • Humidity and wind speed information.
  • Loading indicator during API communication.
  • Error message when weather information cannot be retrieved.

11. Displaying Weather Icons

Weather icons improve the application's visual appearance and help users understand weather conditions quickly. Most weather APIs provide an icon identifier in the JSON response.

Example Weather Icon URL

https://openweathermap.org/img/wn/[email protected]

Displaying an Icon in SwiftUI

AsyncImage(
    url: URL(
        string: "https://openweathermap.org/img/wn/[email protected]"
    )
) { image in
    image
        .resizable()
        .scaledToFit()
} placeholder: {
    ProgressView()
}
.frame(width: 100, height: 100)

For a dynamic application, the icon identifier should be obtained from the API response rather than hardcoded.

12. Integrating Core Location for Current Weather

Core Location allows an iOS application to access the device's geographical coordinates with the user's permission. These coordinates can be used to retrieve weather information for the current location.

Core Location Features

  • Retrieve latitude and longitude.
  • Request location permission from users.
  • Determine the device's current location.
  • Support location-based weather searches.
  • Handle location permission restrictions.

Location Permission Configuration

Add the following privacy description to the application's Info configuration:

NSLocationWhenInUseUsageDescription

Example description:

This app uses your location to display local weather information.

Location-Based API Request

https://api.openweathermap.org/data/2.5/weather?lat=19.0760&lon=72.8777&appid=YOUR_API_KEY&units=metric

The latitude and longitude values in this example represent Mumbai. In a real application, these values should be retrieved from Core Location.

13. Adding Hourly and Daily Weather Forecasts

A useful weather application should provide more than current weather conditions. Forecast functionality allows users to understand expected weather changes throughout the day and over the coming days.

Hourly Forecast Information

  • Expected temperature for each hour.
  • Rain probability.
  • Weather conditions.
  • Wind speed and direction.
  • Hourly weather icons.

Daily Forecast Information

  • Minimum temperature.
  • Maximum temperature.
  • Expected weather conditions.
  • Rainfall probability.
  • Daily weather summary.

Forecast data should be retrieved from the appropriate forecast endpoint supported by the selected weather API provider. The response model must match the provider's actual JSON structure.

14. Implementing Search and City Management

City search functionality allows users to check weather information for different locations without relying exclusively on GPS.

Recommended Features

  1. Provide a city search field.
  2. Validate the entered city name.
  3. Send the city name to the weather API.
  4. Display the returned weather information.
  5. Show an error when the city is not found.
  6. Allow users to search for another city.
  7. Optionally save frequently searched cities.

Example Input Validation

func validateCity(_ city: String) -> Bool {
    return !city.trimmingCharacters(
        in: .whitespacesAndNewlines
    ).isEmpty
}

Input validation prevents unnecessary API requests when the search field is empty.

15. Handling API Errors and Network Failures

Weather applications depend on external servers and internet connectivity. Therefore, developers must handle API failures properly and provide meaningful messages to users.

Common API Errors

Error Possible Cause Recommended Solution
400 Bad Request Invalid request parameters Validate city name and query parameters.
401 Unauthorized Invalid API key Verify API credentials.
404 Not Found City or endpoint not found Check the city name and API endpoint.
429 Too Many Requests API request limit exceeded Reduce unnecessary requests and respect provider limits.
500 Server Error Weather service problem Retry later and show a friendly message.
Network Error No internet connection Check connectivity and provide retry functionality.

Best Practices for Error Handling

  • Use do-catch blocks for throwing operations.
  • Validate HTTP response status codes.
  • Handle invalid JSON responses.
  • Show understandable error messages.
  • Provide a retry option.
  • Avoid repeatedly sending requests when the server is unavailable.
  • Preserve previously loaded weather information when appropriate.

16. Adding Loading States and Refresh Functionality

Loading states improve the user experience by informing users that the application is retrieving weather information.

Loading State Implementation

if viewModel.isLoading {
    ProgressView("Fetching weather data...")
        .padding()
}

Refresh Functionality

Users should be able to refresh the displayed weather information when required. SwiftUI provides the refreshable modifier for views such as List and ScrollView.

ScrollView {
    // Weather information
}
.refreshable {
    await viewModel.fetchWeather(city: city)
}

Refreshing should trigger a new API request and update the displayed weather information after the response is received.

17. Implementing Weather Data Caching

Caching stores previously retrieved weather information so the application can display useful data without making unnecessary network requests.

Benefits of Caching

  • Reduces repeated API calls.
  • Improves application performance.
  • Helps display previously loaded information when offline.
  • Reduces unnecessary network traffic.
  • Can help manage API usage limits.

Possible Caching Approaches

Technology Purpose
URLCache HTTP response caching.
UserDefaults Simple preferences and small cached values.
SwiftData Persistent storage of structured weather records.
FileManager Saving cached JSON files locally.

Cached weather information should include a timestamp so the application can identify whether the data is still reasonably fresh.

18. Improving Weather App UI and User Experience

A weather application should be simple, visually appealing, and easy to navigate. The most important weather information should be displayed prominently.

UI Design Recommendations

  • Use readable fonts and appropriate text sizes.
  • Display temperature prominently.
  • Use weather icons that match current conditions.
  • Apply suitable background colors.
  • Group related weather information into cards.
  • Maintain consistent spacing and alignment.
  • Support light and dark appearances.
  • Use accessible labels for important interface elements.
  • Ensure the interface adapts to different iPhone screen sizes.

19. Testing the Weather Application

Testing ensures that the application retrieves accurate information, handles errors correctly, and provides a smooth user experience.

Important Testing Scenarios

Test Case Expected Result
Search for Mumbai Displays Mumbai weather information.
Search for Delhi Displays Delhi weather information.
Enter an invalid city Displays an appropriate error.
Disable internet connection Displays a network error or cached data.
Use an invalid API key Handles authentication failure.
Refresh weather information Fetches updated data.
Deny location permission Allows manual city search.
Rotate or resize the interface Maintains a usable layout.

Testing Tools

  • Xcode Simulator: Tests the application on simulated iPhone devices.
  • Xcode Debugger: Identifies runtime issues.
  • Console Logs: Helps inspect API requests and errors.
  • Instruments: Helps analyze performance and resource usage.
  • XCTest: Supports unit and application testing.

20. Common Problems and Troubleshooting

Problem 1: Weather Data Is Not Loading

Possible Reasons: Incorrect API URL, invalid credentials, or internet connectivity problems.

Solution: Verify the request URL, API key, network connection, and HTTP status code.

Problem 2: JSON Decoding Error

Possible Reasons: The Swift model does not match the JSON response structure.

Solution: Inspect the actual API response and update the Codable model accordingly.

Problem 3: Temperature Is Incorrect

Possible Reasons: Incorrect measurement units or incorrect temperature conversion.

Solution: Verify the API unit parameter and display formatting.

Problem 4: Weather Icon Is Not Displayed

Possible Reasons: Invalid icon identifier or incorrect image URL.

Solution: Check the API response and construct the image URL using the correct icon identifier.

Problem 5: Application Shows Old Weather Data

Possible Reasons: Cached response or missing refresh request.

Solution: Check cache policies, timestamps, and refresh implementation.

21. Security and Performance Best Practices

  • Use HTTPS for all API communication.
  • Protect API credentials using secure configuration and backend services where appropriate.
  • Never commit secret credentials to source control.
  • Validate all API responses before displaying information.
  • Use asynchronous networking to keep the interface responsive.
  • Avoid unnecessary repeated API calls.
  • Implement reasonable caching strategies.
  • Handle permission requests transparently.
  • Monitor API usage and service limits.
  • Test the application on real iOS devices.

22. Practical Project: Complete Weather App

The practical project involves building a functional weather application using SwiftUI and REST API integration.

Project Requirements

  • Create an iOS project using Xcode.
  • Integrate a weather API provider.
  • Create Codable weather data models.
  • Implement API requests using URLSession.
  • Display current temperature and conditions.
  • Implement city-based weather search.
  • Integrate Core Location for current-location weather.
  • Display weather icons.
  • Add humidity, pressure, and wind information.
  • Implement loading and error states.
  • Add refresh and caching functionality.
  • Test the application on an iOS simulator.

Expected Project Output

At the end of the project, students should have a working weather application that retrieves real-time weather information from an external REST API and displays the information through a responsive SwiftUI interface.

23. Advanced Features to Extend the Project

After completing the basic weather application, developers can add more advanced features to improve functionality.

  • Multiple Cities: Save and manage weather information for multiple locations.
  • Weather Alerts: Display severe weather notifications when supported by the provider.
  • Interactive Charts: Visualize temperature changes using Swift Charts.
  • Widgets: Display weather information using WidgetKit.
  • Push Notifications: Send relevant weather alerts through a notification service.
  • Apple Watch Support: Extend weather information to watchOS.
  • Offline Mode: Display previously cached weather information.
  • Localization: Support multiple languages and measurement preferences.

24. Practice Exercises

  1. Create a weather application that displays the current temperature of a selected city.
  2. Integrate a weather API using URLSession.
  3. Create Swift Codable structures for parsing JSON responses.
  4. Add a search field for different cities.
  5. Display humidity, wind speed, and atmospheric pressure.
  6. Integrate Core Location to retrieve local weather information.
  7. Display weather icons dynamically using API icon identifiers.
  8. Implement loading indicators and error messages.
  9. Add a refresh feature to retrieve updated weather data.
  10. Implement local caching for previously fetched weather information.

25. Interview Questions and Answers

Q1. What is a REST API?

Answer: A REST API is a web service interface that allows applications to exchange information using HTTP methods and resource-based URLs.

Q2. What is URLSession in iOS?

Answer: URLSession is an Apple networking API used to perform HTTP requests, download information, and communicate with remote servers.

Q3. What is JSON parsing?

Answer: JSON parsing is the process of converting JSON-formatted data into application-readable objects or structures.

Q4. What is the purpose of Codable?

Answer: Codable allows Swift types to encode and decode data formats such as JSON.

Q5. Why is async/await used in weather applications?

Answer: It makes asynchronous API operations easier to write and manage without blocking the user interface.

Q6. What is Core Location?

Answer: Core Location is an Apple framework used to obtain geographical information such as latitude and longitude.

Q7. Why should API keys be protected?

Answer: API keys authenticate requests. If exposed publicly, unauthorized users may consume the application's API quota or misuse the service.

Q8. What is MVVM architecture?

Answer: MVVM stands for Model-View-ViewModel. It separates data, interface, and presentation logic to improve code organization and maintainability.

Q9. What is API caching?

Answer: API caching stores previously retrieved responses to reduce repeated requests and improve application performance.

Q10. How can an iOS application handle network failures?

Answer: By using error handling, checking HTTP status codes, monitoring network conditions, displaying useful messages, and providing retry functionality.

26. Quick Revision

Concept Key Point
REST API Communication between the application and weather server.
URLSession Performs HTTP networking operations.
JSON Data format returned by the weather service.
Codable Converts JSON into Swift data models.
async/await Manages asynchronous API requests.
Core Location Retrieves device location coordinates.
SwiftUI Builds the weather application interface.
MVVM Separates application data and presentation logic.
Error Handling Manages API and networking failures.
Caching Stores previously retrieved weather information.

27. Conclusion

Developing a Weather App Using REST API Integration is an important practical project in iOS application development. It provides hands-on experience with external API communication, URLSession, JSON decoding, Swift concurrency, SwiftUI, Core Location, and MVVM architecture.

By completing this project, students gain the ability to develop applications that retrieve real-time information from external services and present it through modern iOS interfaces. The same concepts can also be applied to news applications, stock market applications, travel applications, fitness applications, and other API-driven mobile solutions.


Learn iOS App Development with JustAcademy

Explore professional iOS App Development training and strengthen your practical skills in Swift, SwiftUI, API integration, application development, and real-world projects.

Course Page: Explore iOS App Development Course

Register for a Demo: Book Your Free Course Demo

Visit JustAcademy: www.justacademy.co

Previous Next
whatsapp