Simplify icon path parsing logic

This commit is contained in:
Maurice Parker 2020-05-05 17:14:23 -05:00
parent 2bb20832f8
commit 9cf338f2d9
1 changed files with 10 additions and 13 deletions

View File

@ -80,11 +80,19 @@ public final class RedditFeedProvider: FeedProvider {
} }
public func iconURL(_ urlComponents: URLComponents, completion: @escaping (Result<String, Error>) -> Void) { public func iconURL(_ urlComponents: URLComponents, completion: @escaping (Result<String, Error>) -> Void) {
guard urlComponents.path.hasPrefix("/r/"), let secondElement = extractSecondElement(path: urlComponents.path) else { guard urlComponents.path.hasPrefix("/r/") else {
completion(.failure(RedditFeedProviderError.unknown)) completion(.failure(RedditFeedProviderError.unknown))
return return
} }
let splitPath = urlComponents.path.split(separator: "/")
guard splitPath.count > 1 else {
completion(.failure(RedditFeedProviderError.unknown))
return
}
let secondElement = String(splitPath[1])
let api = "/r/\(secondElement)/about.json" let api = "/r/\(secondElement)/about.json"
fetch(api: api, parameters: [:], resultType: RedditSubreddit.self) { result in fetch(api: api, parameters: [:], resultType: RedditSubreddit.self) { result in
@ -315,18 +323,7 @@ private extension RedditFeedProvider {
completion(error) completion(error)
} }
} }
func extractSecondElement(path: String) -> String? {
let scanner = Scanner(string: path)
if let _ = scanner.scanString("/"),
let _ = scanner.scanUpToString("/"),
let _ = scanner.scanString("/"),
let secondElement = scanner.scanUpToString("/") {
return secondElement
}
return nil
}
static func storeCredentials(username: String, oauthToken: String, oauthRefreshToken: String) throws { static func storeCredentials(username: String, oauthToken: String, oauthRefreshToken: String) throws {
let tokenCredentials = Credentials(type: .oauthAccessToken, username: username, secret: oauthToken) let tokenCredentials = Credentials(type: .oauthAccessToken, username: username, secret: oauthToken)
try CredentialsManager.storeCredentials(tokenCredentials, server: Self.server) try CredentialsManager.storeCredentials(tokenCredentials, server: Self.server)