-
-
Save sturdysturge/141f55781222cfabc20ee9c22dfe7263 to your computer and use it in GitHub Desktop.
This file contains 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
private extension ColourViewModel { | |
var url: URL { URL(string: "http://colormind.io/api/")! } | |
var input: [Input] { | |
let colour1: Input = .integerArray([Int(red1 * Response.max), | |
Int(green1 * Response.max), | |
Int(blue1 * Response.max)]) | |
let colour2: Input = .integerArray([Int(red2 * Response.max), | |
Int(green2 * Response.max), | |
Int(blue2 * Response.max)]) | |
return [colour1, .unknown, .unknown, .unknown, colour2] | |
} | |
var request: URLRequest { | |
var request = URLRequest(url: url) | |
request.httpMethod = "POST" | |
let body = Request(input: input, model: "default") | |
guard let data = try? JSONEncoder().encode(body) else { | |
return request | |
} | |
request.httpBody = data | |
return request | |
} | |
func getResponse() async -> Response { | |
await withUnsafeContinuation { continuation in | |
URLSession.shared.dataTask(with: request) { (data, response, error) in | |
guard let data, let successfulResponse = try? | |
JSONDecoder().decode(Response.self, from: data) else { | |
fatalError("Data not found or Response couldn't be decoded") | |
} | |
continuation.resume(with: .success(successfulResponse)) | |
}.resume() | |
} | |
} | |
struct Response: Codable { | |
static var max: Double { Double(UInt8.max) } | |
let result: [[Int]] | |
func schemeColour(atIndex index: Int) -> Color? { | |
guard result.indices.contains(index), result[index].count == 3 else { | |
return nil | |
} | |
let array = result[index] | |
return Color(red: Double(array[0]) / Self.max, | |
green: Double(array[1]) / Self.max, | |
blue: Double(array[2]) / Self.max) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment