Integrating Third-Party APIs in iOS Swift Applications

I’m having trouble setting up API calls in my Swift iOS project. I’m working on connecting to an external weather service but it doesn’t seem to work. Here’s my current code snippet:

import UIKit

class WeatherService {
    func fetchWeatherData() {
        let apiHeaders = [
            "x-rapidapi-host": "weather-api-service.p.rapidapi.com",
            "x-rapidapi-key": "YOUR_API_KEY_HERE"
        ]
        
        guard let apiURL = URL(string: "https://weather-api-service.p.rapidapi.com/current?city=Paris%252Cfr") else {
            return
        }
        
        var urlRequest = URLRequest(url: apiURL)
        urlRequest.httpMethod = "GET"
        urlRequest.allHTTPHeaderFields = apiHeaders
        urlRequest.timeoutInterval = 15.0
        
        let networkSession = URLSession.shared
        let apiTask = networkSession.dataTask(with: urlRequest) { responseData, urlResponse, requestError in
            if let error = requestError {
                print("Network error: \(error)")
                return
            }
            
            if let httpResp = urlResponse as? HTTPURLResponse {
                print("Status code: \(httpResp.statusCode)")
            }
        }
        apiTask.resume()
    }
}

What’s the correct way to structure this code so it will function properly in a real application?

You’re not doing anything with the response data. Your completion handler gets responseData but never processes it. You need to unwrap that optional data and decode the JSON response. This method should probably be async or use a completion handler to return results to your view controller. I’ve hit this same issue - the API call works but you never see the parsed weather data because there’s no data flow back to the UI. Make this method return a Result type or use async/await if you’re targeting iOS 15+. Also double-check your API key is valid - weather services usually have specific formatting requirements.

You’re not actually processing the data in your completion block. The responseData just sits there - you need to decode it into your weather model struct. That URL encoding looks off too - %252C should probably just be %2C for commas. I’d test the endpoint manually first to make sure it’s returning valid JSON before adding the Swift parsing logic.

Your code isn’t handling the response data or returning anything to the calling code. The network request might work fine, but you can’t see what’s coming back. Add JSON parsing and use completion handlers or delegates to pass the data back. Double-check your API key and endpoint URL - test it in Postman first. I always add error handling for different HTTP status codes when debugging API issues. You’ll also want to wrap this in a proper data model since weather APIs return complex JSON objects.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.