11

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" : "1234@gmail.com",
        "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!!

Praveen Kumar
  • 298
  • 2
  • 15

4 Answers4

7

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

Community
  • 1
  • 1
Qamar
  • 4,959
  • 1
  • 30
  • 49
1

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

var parameters = [
    "first_name": "XXXXX",
    "email" : "1234@gmail.com",
    "password" : "password"]

if let base64String = base64String where !base64String.isEmpty {
    parameters["profile_picture"] = base64String
}
Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
-1

hope this will help you :)

var parameters :[String : AnyObject?] = [
    "first_name": "XXXXX",
    "email" : "1234@gmail.com",
    "password" : "password"]

if let string = base64String where base64String.isEmpty != false {
  parameters["profile_picture"] = string 
} 
Sahil
  • 9,096
  • 3
  • 25
  • 29
  • @ Sahil `"key": nil` this will be treated as an additional [Key:Value] pair. What it is supposed to do with the "profile_picture" value?! – Praveen Kumar Apr 19 '16 at 11:37
  • okay, you mean when you base64String is empty you wana pass nil? – Sahil Apr 19 '16 at 11:47
  • Yes it should, but it gets crashed while unwrapping the value, because it is a nil value. I need to get a success response even if the value is nil. When i tried your code, it says **'valye of type 'Bool' can never be nil, comparison isn't allowed'** – Praveen Kumar Apr 19 '16 at 12:41
  • sorry for that. isEmpty either return false or true – Sahil Apr 19 '16 at 12:49
  • It works!! but if i give a valid image it shows the same result in my response that no image is available. – Praveen Kumar Apr 19 '16 at 12:56
  • what is your base64String value? i mean did you debug your code? – Sahil Apr 19 '16 at 13:39
  • It is a huge encoded string like 8RhCyHNWMoZaZjnv7emSezx.... so on. yes i debug the code and i get the nil value if there is no image and i get this string value if there is a valid image but in my response it is not getting reflected. Do i need to move on to the **Upload Post request** or can i do it here itself?! – Praveen Kumar Apr 19 '16 at 13:52
  • i guess you should use Upload method. – Sahil Apr 19 '16 at 13:53
  • then you need to ask server guy. and you should try hitting api in postman. – Sahil Apr 20 '16 at 04:54
-1

After a very thorough research, I found out it can be done easily through optional chaining and type casting.

The first step it to divide the parameters by type casting it to string and Image and check for the availability of String value and Image value.

let parameters: [String : AnyObject? ] = [
    "first_name": "XXXXX",
    "email" : "1234@gmail.com",
    "password" : "password",
    "profile_pic" : UIImage(named: "logo")]

Do it like this in the request method

for (key, value) in parameters {

                if let value1 = value as? String {
                    multipartFormData.appendBodyPart(data: value1.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
                }
                if let value1 = value as? UIImage {
                  let imageData = UIImageJPEGRepresentation(value1, 1)
                      multipartFormData.appendBodyPart(data: imageData!, name: key, fileName: "logo.png" , mimeType: "image/png")
                    }

You don't have to split the parameters into two, one for the string values and other for the image and also it is unnecessary to convert the image to string. Hope this solution helps!!

Praveen Kumar
  • 298
  • 2
  • 15