mas/MasKit/Controllers/MasStoreSearch.swift

78 lines
2.4 KiB
Swift
Raw Normal View History

2018-12-30 06:57:06 +00:00
//
// MasStoreSearch.swift
// MasKit
//
// Created by Ben Chatelain on 12/29/18.
// Copyright © 2018 mas-cli. All rights reserved.
//
/// Manages searching the MAS catalog through the iTunes Search and Lookup APIs.
2019-01-05 00:54:00 +00:00
public class MasStoreSearch: StoreSearch {
2019-01-06 19:26:08 +00:00
private let networkManager: NetworkManager
2019-01-02 05:44:33 +00:00
/// Designated initializer.
2019-01-06 19:26:08 +00:00
public init(networkManager: NetworkManager = NetworkManager()) {
self.networkManager = networkManager
2019-01-02 05:44:33 +00:00
}
2018-12-30 06:57:06 +00:00
/// Searches for an app.
///
/// - Parameter appName: MAS ID of app
/// - Returns: Search results list of app. List will have no records if there were no matches. Never nil.
/// - Throws: Error if there is a problem with the network request.
public func search(for appName: String) throws -> SearchResultList {
guard let url = searchURL(for: appName)
else { throw MASError.urlEncoding }
let result = networkManager.loadDataSync(from: url)
// Unwrap network result
guard case let .success(data) = result
else {
if case let .failure(error) = result {
throw error
}
throw MASError.noData
}
do {
let results = try JSONDecoder().decode(SearchResultList.self, from: data)
return results
} catch {
throw MASError.jsonParsing(error: error as NSError)
}
}
2019-01-02 05:44:33 +00:00
/// Looks up app details.
///
/// - Parameter appId: MAS ID of app
/// - Returns: Search result record of app or nil if no apps match the ID.
/// - Throws: Error if there is a problem with the network request.
public func lookup(app appId: String) throws -> SearchResult? {
2019-01-06 19:26:08 +00:00
guard let url = lookupURL(forApp: appId)
else { throw MASError.urlEncoding }
2019-01-06 19:26:08 +00:00
let result = networkManager.loadDataSync(from: url)
// Unwrap network result
guard case let .success(data) = result
2019-01-02 05:44:33 +00:00
else {
2019-01-06 19:26:08 +00:00
if case let .failure(error) = result {
throw error
}
throw MASError.noData
2019-01-02 05:44:33 +00:00
}
do {
let results = try JSONDecoder().decode(SearchResultList.self, from: data)
2019-01-02 05:44:33 +00:00
guard let searchResult = results.results.first
else { return nil }
2019-01-02 05:44:33 +00:00
return searchResult
} catch {
throw MASError.jsonParsing(error: error as NSError)
}
2019-01-02 05:44:33 +00:00
}
2018-12-30 06:57:06 +00:00
}