Skip to content

Instantly share code, notes, and snippets.

@cliss
Created May 21, 2022 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cliss/bcdc296cfee626b36c4f84bcec449a87 to your computer and use it in GitHub Desktop.
Save cliss/bcdc296cfee626b36c4f84bcec449a87 to your computer and use it in GitHub Desktop.
Fetching Ratings
import Foundation
import Combine
public struct RatingsFetcher {
/// Asynchronously gets the number of ratings for the current version of the given app.
/// - Parameter appId: App ID to look up
/// - Returns: Count of ratings for the current version
public static func ratingsForCurrentVersion(appId: Int) async throws -> Int {
guard let url = URL(string: "https://itunes.apple.com/lookup?id=\(appId)") else {
return 0
}
let (data, _) = try await URLSession.shared.data(from: url)
let ratingsInfo = try JSONDecoder().decode(RatingsInfo.self, from: data)
return ratingsInfo.results.first?.userRatingCountForCurrentVersion ?? 0
}
/// Gets a `Publisher` which in turn gets the number of ratings for
/// the current version of the given app.
/// - Parameter appId: App ID to look up
/// - Returns: Publisher which signals with the count of ratings for the current version
static func ratingsPublisherForCurrentVersion(appId: Int) -> AnyPublisher<Int, Error> {
guard let url = URL(string: "https://itunes.apple.com/lookup?id=\(appId)") else {
return Just(0).setFailureType(to: Error.self).eraseToAnyPublisher()
}
return URLSession.shared.dataTaskPublisher(for: url)
.tryMap { (data, _) -> Int in
let ratingsInfo = try JSONDecoder().decode(RatingsInfo.self, from: data)
return ratingsInfo.results.first?.userRatingCountForCurrentVersion ?? 0
}
.eraseToAnyPublisher()
}
private struct RatingsInfo: Decodable {
let resultCount: Int
let results: [RatingsInfoResult]
}
private struct RatingsInfoResult: Decodable {
let userRatingCountForCurrentVersion: Int
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment