This is my create group function:
webService.createGroup(url: apiUrl, requestBody: requestBody) { result in
switch result {
case .success(let response):
print("Group created successfully:", response)
completion(.success("Group created successfully"))
case .failure(let error):
print("Error creating group:", error)
return
}
}
}
func createGroup(url: URL, requestBody: [String: Any], completion: @escaping (Error?) -> Void) {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: requestBody)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
do {
if let error = error {
print("Error creating group: \(error)")
completion(error)
return
}
guard let httpResponse = response as? HTTPURLResponse else {
print("Error: No HTTP response")
completion(WebService.NetworkError.invalidResponse)
return
}
print("HTTP Response Status Code: \(httpResponse.statusCode)")
guard (200...299).contains(httpResponse.statusCode) else {
print("Error: Unexpected HTTP response status code")
// Print response data for debugging purposes
if let data = data {
let responseString = String(data: data, encoding: .utf8) ?? "Unable to convert data to string"
print("HTTP Response Data: \(responseString)")
}
completion(WebService.NetworkError.invalidResponse)
return
}
completion(nil)
} catch {
print("Error in createGroup: \(error)")
completion(error)
}
}
task.resume()
}
That was my web service function that I used to make the create group function in my grouplistviewmodel.
The error is: Type '(any Error)?' has no member 'success'
It is on line:
case .success(let response):
and
case .failure(let error):
Any help is much appreciated thank you!
The error you get is because your completion handler only returns a type Error?
from your func createGroup(...)
,
and that, as the error says, does not have a success
, it is either an Error
or nil
.
So try something like this:
webService.createGroup(url: apiUrl, requestBody: requestBody) { error in
if error == nil {
print("Group created successfully:")
} else {
print("Error creating group:", error)
}
}
Typically you would have completion with something like ... completion: @escaping (Result<Data, Error?>) -> Void)
, but it's up to you what you want to do.