Search code examples
iosjsonswiftpostalamofire

send array of json objects in ios


I have a post request that has a body like this

 {
   "cars": [
       {
           "id": 126,
           "drivers": [
                 "[email protected]"
           ]
       },
       {
           "id": 128,
           "drivers": [
                   "[email protected]"
           ]
       }
   ]
}

the id and drivers are changeable, and I got them from another api so how to send this body with the post request?

on the other hand I have a textField that takes another email of driver, I want to change drivers when this request was sent.

example:

 {
   "cars": [
       {
           "id": 126,
           "drivers": [
                 "[email protected]",
                 "[email protected]"
           ]
       },
       {
           "id": 128,
           "drivers": [
                   "[email protected]"
           ]
       }
   ]
}

As you can see I want to update the drivers to the new one when I tap add button on the specific textField depends on the id.

This is my code

public static func loadDrivers(owners: [Owner], drivers: [Driver], driverEmail: String!, i: Int, completion: @escaping (_ code:Int?)-> Void) {

        let headers: HTTPHeaders = [
            "Accept": "application/json"
        ]

        var para2 = [String : [[String : Any]]]()

        para2 = [

            "cars": [
                [
                    "id": owners[i].id,
                    "drivers": [
                        drivers[i].email,
                        driverEmail
                    ]
                ]
            ]
        ]

            if driverEmail != nil {

            Alamofire.request(APIHelper.BASE_URL + APIHelper.API.ADD_DRIVERS.rawValue, method: .post, parameters: para2, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in

                switch response.result {
                case .success:
                    let json = response.result.value as? NSDictionary
                    let code = json!["code"]
                    completion(code as? Int)
                case .failure(let error):
                    print(error)
                    completion(nil)
                    return
                }
            }
        }
    }

Thanks in advance


Solution

  • This question is screaming Codable protocol at me, so here it goes. The Codable protocol makes using true Swift objects to generate JSON a real breeze. Try this in a Playground:

    import Cocoa
    
    struct Car : Codable {
        let id:Int
        let drivers:[String]    // you will want to improve on this
    }
    
    struct Mobiles : Codable {
        let cars:[Car]
    }
    
    var mobiles = Mobiles(cars:[Car(id:126, drivers:["[email protected]", "[email protected]"]),
        Car(id:128, drivers:["[email protected]"])])
    
    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted
    
    print(String(data:try encoder.encode(mobiles), encoding:.utf8)!)
    

    Since you should be able to employ Swift on both ends of this equation it is easy to see that this requires a lot less code than your example.