Created
May 21, 2022 00:35
-
-
Save cliss/bcdc296cfee626b36c4f84bcec449a87 to your computer and use it in GitHub Desktop.
Fetching Ratings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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