forked from shadowfacts/Tusker
Shadowfacts
79f44c9b58
instead of enum Additional categories can be added, which would cause a crash when decoding. As the category isn't used for anything, storing it as an enum value is not necessary.
65 lines
2.0 KiB
Swift
65 lines
2.0 KiB
Swift
//
|
|
// InstanceSelector.swift
|
|
// Pachyderm
|
|
//
|
|
// Created by Shadowfacts on 9/15/19.
|
|
// Copyright © 2019 Shadowfacts. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
public class InstanceSelector {
|
|
|
|
private static let decoder = JSONDecoder()
|
|
|
|
public static func getInstances(category: String?, completion: @escaping Client.Callback<[Instance]>) {
|
|
let url: URL
|
|
if let category = category {
|
|
url = URL(string: "https://api.joinmastodon.org/servers?category=\(category)")!
|
|
} else {
|
|
url = URL(string: "https://api.joinmastodon.org/servers")!
|
|
}
|
|
let request = URLRequest(url: url)
|
|
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
|
|
if let error = error {
|
|
completion(.failure(error))
|
|
return
|
|
}
|
|
guard let data = data,
|
|
let response = response as? HTTPURLResponse else {
|
|
completion(.failure(Client.Error.invalidResponse))
|
|
return
|
|
}
|
|
guard response.statusCode == 200 else {
|
|
completion(.failure(Client.Error.unknownError))
|
|
return
|
|
}
|
|
guard let result = try? decoder.decode([Instance].self, from: data) else {
|
|
completion(.failure(Client.Error.invalidModel))
|
|
return
|
|
}
|
|
completion(.success(result, nil))
|
|
}
|
|
task.resume()
|
|
}
|
|
|
|
}
|
|
|
|
public extension InstanceSelector {
|
|
struct Instance: Codable {
|
|
public let domain: String
|
|
public let description: String
|
|
public let proxiedThumbnailURL: URL
|
|
public let language: String
|
|
public let category: String
|
|
|
|
enum CodingKeys: String, CodingKey {
|
|
case domain
|
|
case description
|
|
case proxiedThumbnailURL = "proxied_thumbnail"
|
|
case language
|
|
case category
|
|
}
|
|
}
|
|
}
|