Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass a nil value for one of the parameter in alamofire Post request

I would like to pass a nil value i.e., optional to one of the parameter value. And it must proceed with the nil value in the Alamofire Post request .It would be helpful if you tell me how to proceed next?

    let image: UIImage = UIImage()
    let imageData = UIImagePNGRepresentation(image)
    let base64String = imageData?.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)

    let parameters = [
        "first_name": "XXXXX",
        "email" : "[email protected]",
        "password" : "password",
        "profile_picture" : base64String]

Alamofire.request(.POST, "http://abc/public/user/register", parameters: parameters, encoding: .JSON, headers: nil)

        .progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
            print(totalBytesWritten)

            // This closure is NOT called on the main queue for performance
            // reasons. To update your ui, dispatch to the main queue.
            dispatch_async(dispatch_get_main_queue()) {
                print("Total bytes written on main queue: \(totalBytesWritten)")
           }
        }
        .responseJSON { response in
            debugPrint(response)
    }

The response should gets succeeded even if the profile_pictures is empty. I know it can be done with optional chaining but don't know how to proceed!!

like image 383
Praveen Kumar Avatar asked Apr 19 '16 10:04

Praveen Kumar


2 Answers

By passing nil or uninitialized optional parameter Server will get Optional

You can pass NSNull() to dictionary

try this, like

var params = ["paramA","valueA"] if imageBase64 == nil {   parms["image"] = NSNull()} else {   params["image"] = imageBase64 }

swiftyjson also handle null as NSNull

also there is good reference here null / nil in swift language

like image 117
Qamar Avatar answered Nov 15 '22 23:11

Qamar


I think your simplest answer would be to add "profile_picture" as a second step.

var parameters = [
    "first_name": "XXXXX",
    "email" : "[email protected]",
    "password" : "password"]

if let base64String = base64String where !base64String.isEmpty {
    parameters["profile_picture"] = base64String
}
like image 42
Jeffery Thomas Avatar answered Nov 16 '22 00:11

Jeffery Thomas