0

I have the following code running in a playground that supposed to print an array of 4 clues based on a random category ID. The category ID and the Correct URL used to get the clues are always printed correctly However, the clue results are printed intermittently sometimes its successful other times. Can anyone help me figure out why it sometimes does not print the array of clues yet the URL is correct?

import Foundation import Combine // MARK: - ClueElement struct ClueElement: Codable { let id: Int let answer, question: String let value: Int let categoryID: Int let category: Category enum CodingKeys: String, CodingKey { case id, answer, question, value case categoryID = “category_id” case category } } // MARK: - Category struct Category: Codable { let id: Int let title: String let cluesCount: Int enum CodingKeys: String, CodingKey { case id, title case cluesCount = “clues_count” } } enum HTTPError: LocalizedError { case statusCode case post } typealias Clue = [ClueElement] var cancellable: AnyCancellable? func loadData() { let url1 = URL(string: “http://www.jservice.io/api/random”)! cancellable = URLSession.shared.dataTaskPublisher(for: url1) .map { $0.data } .decode(type: Clue.self, decoder: JSONDecoder()) .tryMap { category in guard let categoryID = category.first?.categoryID else { throw HTTPError.post} guard let cluesCount = category.first?.category.cluesCount else { throw HTTPError.post} print(“\(categoryID)“) return (categoryID,cluesCount) } .flatMap { (categoryID,cluesCount) in return getClues(for: categoryID, cluesCount: cluesCount) } .receive(on: DispatchQueue.main) .sink(receiveCompletion: { completion in }) { clues in print(clues) } } func getClues(for id: Int, cluesCount: Int) -> AnyPublisher<Clue, Error> { let url = URL(string: “http://www.jservice.io/api/clues?category=\(id)&offset=\(cluesCount - 4)“)! print(url) return URLSession.shared.dataTaskPublisher(for: url) .map { $0.data } .decode(type: Clue.self, decoder: JSONDecoder()) .receive(on: DispatchQueue.main) .eraseToAnyPublisher() } loadData() 

1 Answer 1

1

Put a print statement in your receiveCompletion: closure and you will learn why your code doesn't print sometimes.

.sink( receiveCompletion: { completion in print(completion) }, receiveValue: { clues in print(clues) } ) 

I saw this when I did it:

failure(Swift.DecodingError.valueNotFound(Swift.Int, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 2", intValue: 2), CodingKeys(stringValue: "value", intValue: nil)], debugDescription: "Expected Int value but found null instead.", underlyingError: nil))) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.