3

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.})
8
  • 1
    The following line doesn't make sense. request.httpBody = try? JSONSerialization.data(withJSONObject: [parameters]) Commented Jul 13, 2021 at 4:44
  • Why are you saying that? Commented Jul 13, 2021 at 4:46
  • you used query item data just pass that in body like request.httpBody = queryItemsData Commented Jul 13, 2021 at 6:29
  • Please show us the API spec. Whatever you send in the body of the POST request, needs to be in the exact form and content type the backend expects. For example, you showed us a JSON Object, containing one element "watermarks". You can send the object or the array or the object wrapped in an array, but unless you show us what the backend expects, you cannot expect an answer that helps. Commented Jul 13, 2021 at 9:14
  • @CouchDeveloper that is what the backend expects! The first chunk of code is what the service is expecting as parameters. That is an example of what has to be passed Commented Jul 14, 2021 at 2:12

2 Answers 2

2

Try do like this

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 {
                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)
                        completion(.failure(errorResponse as! Error))
                    }
                }catch{
                    completion(.failure(error))
                }
            }
        }
    }
    task.resume()
}
Sign up to request clarification or add additional context in comments.

Comments

1

initialise Variables

var invitationsArray = Array<[String: Any]>()
var invitations = Array<[String: Any]>()

Logic

    invitations = [["friend_id": "\(each.friendId!)", "invited_type": "friend"]]
                    invitationsArray.append(contentsOf: invitations)

Set variables

let params: [String: Any] = [
            "user_id":Global.shared.currentUserLogin.id,
            "ride_name": planARide.name!,
            "ride_description": planARide.description!,
            "ride_type": planARide.rideType!,
            "ride_date_and_time": planARide.rideDate!,
            "ride_city": planARide.city!,
            "ride_meeting_spot": planARide.rideMeetingSpot!,
            "ride_meeting_latitude": planARide.latitude!,
            "ride_meeting_longitude": planARide.longitude!,
            "ride_intensity": planARide.rideIntensity!,
            "time_length_of_ride": planARide.rideTime!,
            "reoccuring_ride": planARide.rideReccurring!,
            "special_instructions": planARide.specialInstruction!,
            "open_ride_to_biking_community": planARide.openRideToBikingCommunity!,
            "invitations": invitationsArray
        ]

1 Comment

I tried that but didn't work. I updated the question with the things I'm getting

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.