CodexBloom - Programming Q&A Platform

Unable to Fetch Remote JSON Data on iOS 17 with Combine Framework

๐Ÿ‘€ Views: 21 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-09-06
ios combine urlsession json swift

I'm having a hard time understanding This might be a silly question, but Hey everyone, I'm running into an issue that's driving me crazy... I'm having trouble fetching JSON data from a remote API using the Combine framework in my iOS 17 app. I set up my `URLSession` to publish the data, but I keep getting a 'No value found for key' error when I try to decode the response into my model. Hereโ€™s a simplified version of my code: ```swift import Combine import Foundation struct MyModel: Codable { let id: Int let name: String } class DataFetcher { var cancellables = Set<AnyCancellable>() func fetchData() { guard let url = URL(string: "https://api.example.com/data") else { return } URLSession.shared.dataTaskPublisher(for: url) .map { $0.data } .decode(type: [MyModel].self, decoder: JSONDecoder()) .receive(on: DispatchQueue.main) .sink(receiveCompletion: { completion in switch completion { case .finished: print("Finished fetching data") case .failure(let error): print("Error fetching data: \(error)") } }, receiveValue: { models in print(models) }) .store(in: &cancellables) } } ``` When I run this, I see the error message: `DecodingError.keyNotFound(CodingKeys(stringValue: "name", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"name\", intValue: nil) ("name"), or the value is not convertible to String.", underlyingError: nil))`. Iโ€™ve double-checked the structure of the JSON, and it looks like this: ```json [ { "id": 1, "name": "Item 1" }, { "id": 2, "name": "Item 2" } ] ``` The keys seem to match my model, so Iโ€™m not sure why the decoding fails. Iโ€™ve also tried logging the raw data just before decoding, and it looks correct. Any suggestions on what might be going wrong or how to properly debug this issue? I ensured that I'm on iOS 17 and using the latest Xcode version. This is part of a larger application I'm building. Am I missing something obvious? What am I doing wrong? This is for a CLI tool running on Debian. I recently upgraded to Swift latest. How would you solve this?