Programmatically count App Store ratings

Overcast, one of my favorite iOS apps, has a thing where it shows how many App Store ratings it has. I don’t know if it was the first app to do this, but it was the first I’d seen. Anyway, I wanted that functionality in one of my apps.

As it turns out, the App Store has an API for getting this information. All you need to do is download from (where APP_ID is the ID of the app you’re interested in). This gives you a pile of JSON which contains, among many other things, the count of ratings for the app.

So, download some JSON over https, and parse it. Simple. I wrote a little class to do this. There’s one function, which looks something like this:

func fetchNumberOfRatings(appID: String, completion: @escaping (Bool, Int) -> ()) {
    let appStoreURL = URL(string: "\(appID)")
    let task = URLSession.shared.dataTask(with: appStoreURL!, completionHandler: { (data, response, error) in
        var gotResult = false
        var ratingsCount = 0
        if error == nil && data != nil,
            let jsonResult = (try? JSONSerialization.jsonObject(with: data!, options:[])) as? NSDictionary,
            let results = jsonResult["results"] as? NSArray,
            results.count > 0,
            let result = results[0] as? NSDictionary,
            let numberOfTimes = result["userRatingCountForCurrentVersion"] as? Int
            // Got it!
            gotResult = true
            ratingsCount = numberOfTimes
        DispatchQueue.main.async {
            completion(gotResult, ratingsCount)

It’s pretty self-explanatory. It uses NSURLSession to download the JSON, parses it with NSJSONSerialization, and calls a completion proc you provide. You’d call it like:

FARatingCounter.defaultCounter.fetchNumberOfRatings(appID: appInfo.ID) {
    success, number in
    // Do something with number

I just posted this to GitHub, along with a little sample app showing how to use it. Check it out here.