I currently have two classes in my app.
One class stores important values in variables (ex. size, color, width) that correspond to user inputs.
Another class initiates a URLRequest to an API in order to fetch data.
My goal is to make a parameter in the URL change depending on the values stored in the variable of the first class.
For instance, the URL looks like this: "www.google.com/docs/(VAR)" I made VAR into a variable in the class with an API request and I'm trying to mutate it with conditional statements using variables from the first class.
Unfortunately, this is giving me an error and I am unable to transfer data between two classes.
Any suggestions?
Here is the code for the first class:
import Foundation
class Product: ObservableObject, CustomStringConvertible {
@Published var color = ""
@Published var size = ""
@Published var finish = ""
@Published var cut = ""
@Published var length = ""
@Published var type = ""
var description: String {
"\(size) - \(finish) - \(cut) -\(length)"
}
}
Here is the code for the APIRequest
import Foundation
class APIRequest: ObservableObject {
@Published
var lengthOptions: [String] = []
init () {
fetchLengths { lengths in
self.lengthOptions = lengths[0].OptionList.map { $0.OptionName }
}
}
private func fetchLengths (completion: @escaping ([OptionsHead]) -> ()) {
let catalogID = 1877
// how can I change catalogID based on Product class variables
guard let url = URL(string: "blablaAPI.com/Products/\(catalogID)/Options?limit=1&offset=3")
else {
fatalError("URL is not correct")
}
var request = URLRequest(url: url)
request.addValue("12345", forHTTPHeaderField: "PrivateKey")
request.addValue("https://www.blaaaaa.com", forHTTPHeaderField: "SecureURL")
request.addValue("12345", forHTTPHeaderField: "Token")
request.httpMethod = "GET" // "POST", "PUT", "DELE"
URLSession.shared.dataTask(with: request) { data, _, _ in
let outputs = try!
JSONDecoder().decode([OptionsHead].self, from: data!)
DispatchQueue.main.async {
completion(outputs)
}
}.resume()
}
}
you could try passing the Product into you APIRequest class, to change the catalogID based on Product class variables, like this:
class APIRequest: ObservableObject {
@Published var lengthOptions: [String] = []
@ObservedObject var product: Product
init (product: Product) {
self.product = product
fetchLengths { lengths in
self.lengthOptions = lengths[0].OptionList.map { $0.OptionName }
}
}
private func fetchLengths (completion: @escaping ([OptionsHead]) -> ()) {
var catalogID = 1877
// how can I change catalogID based on Product class variables
if product.type == "some type" {
catalogID = 1234
} else {
catalogID = 4321
}
....
}