I'm trying to pass an array of parameters that looks like this:
{
"watermarks": [
{
"email" : "correo_user",
"event_type" : "app",
"watermark" : "marcaAgua",
"date" : "date",
"location" : "location",
"segment" : 1,
"time" : "time",
"country" : "country",
"city" : "city"
}
]
}
I don't know how to pass it as an array of objects because I have never done it before. This is the code that I'm currently using:
func marcaAgua(parameters: [String: Any],
completion: @escaping (Result<[MarcaAguaResData], Error>)-> Void) {
let urlString = baseUrl + "events"
guard let url = URL(string: urlString) else {
completion(.failure(NetworkingError.badUrl))
return
}
var request = URLRequest(url: url)
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters)
request.httpMethod = "POST"
request.setValue("Bearer \(token_login)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
guard let unwrappedResponse = response as? HTTPURLResponse else {
completion(.failure(NetworkingError.badResponse))
return
}
switch unwrappedResponse.statusCode {
case 200 ..< 300:
print("success")
default:
print("failure")
}
if let unwrappedError = error {
completion(.failure(unwrappedError))
return
}
if let unwrappedData = data {
print("QQQQQ")
print(unwrappedData)
do{
let json = try JSONSerialization.jsonObject(with: unwrappedData, options:.allowFragments)
if let successRes = try? JSONDecoder().decode([MarcaAguaResData].self, from: unwrappedData){
completion(.success(successRes))
}else{
let errorResponse = try JSONDecoder().decode([MarcaAguaErrorResponse].self, from: unwrappedData)
print("Error \(errorResponse)")
completion(.failure(errorResponse as! Error))
}
}catch{
print("AAA")
completion(.failure(error))
}
}
}
}
task.resume()
}
When I pass the parameters to the function when I call it, I pass them as a dictionary of type [String:Any]. This is an example of it:
let signupQueryData : [String : Any] = [
"watermarks": [
"email" : correo_user as String,
"event_type" : "app" as String,
"watermark" : marcaAgua as String,
"date" : "\(dateActual) \(hour):\(minutes)" as String,
"location" : latitudYLongitud as String,
"segment" : 1 as Int,
"time" : "\(hour):\(minutes)" as String,
"country" : "\(qlq)" as String,
"city" : "Caracas" as String
]
]
And this is what it prints of parameters in the function marcaAgua:
["watermarks": ["time": "22:10", "segment": 1, "location": "location", "email": "mail", "event_type": "app", "watermark": "e356eaadcb3aa4a1049441fc48d83a22", "date": "13.07.2021 22:10", "country": "Venezuela", "city": "Caracas"]]
When I do that, I get the following error:
failure(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})
request.httpBody = queryItemsData