Search code examples
iosobjective-ccocoa-touchnsdatansjsonserialization

How do I POST raw NSData as well as some NSStrings to my server?


I have a large piece of NSData I want to send to my server, but I also want to send a string dictionary of string keys mapped to string keys.

How do I POST both in the same request?

Almost all guides show wrapping it in an NSDictionary then using NSJSONSerialization to turn it into NSData then POST that, but I can't have NSData and NSStrings in the same NSDictionary it just crashes, so I assume I have to keep it separate, but how would that look?

Essentially how do I serialize JSON into NSData and then also have a separate NSData blob with it?


Solution

  • let body = NSMutableDictionary()
    body.setValue("myString" forKey: "stringType")
    body.setValue(data?.base64EncodedString(options: .lineLength64Characters) forKey: "dataType")
    

    In this way you can have both data and string in the dictionary. Here 'data?.base64EncodedString(options: .lineLength64Characters)' returns you a string with base64 encoding. So your dictionary contains only string and at server end you have to covert it back to data.

    Hope it solves your issue