Create NSDictionary format as per JSON Request in POST method - swift

I need to POST datas to JSON. I don't know how to convert to NSDictionary for some complicated JSON format.
Format is below:
//1.JSON FORMAT
{
"username": "qqq_qq#qqq.qq",
"password": "******"
}
//In Swift:
var params = ["username": nameTxtFld.text, "password" : passTxtFld.text] as Dictionary<String, String>
//WORKING
//2. JSON FROMAT
{
"name":"qqq",
"emailId":"qqq_qq#qqq.qq",
"user":{
"password":"****",
"confirmPassword":"****"
}
}
//In Swift
var parameters = ["userName": nameTxtFld.text, "email": emailTxtFld.text, "user" : ["password" : passTxtFld.text, "confirmPassword" : confPassTxtFld.text]] as Dictionary<String, String, String>
//Error
//Unprintable ASCII character found in source file
Kindly guide me? How to covert this format in NSDictionary

When you want to send a JSON format request to web server, why don't you create a String with the formatted keys and values like #"username=xxxx&password=xxx" and then while adding this string to NSMUtableURLRequest class, convert this string to NSData and then add it.
This will be format we can use while sending POST type of request.

Related

Swift-JWT decoding issue

I am using the Swift-JWT Cocoapod file, when I try to encode a particular claim struct, it gives me a cryptogram, when I check in this cryptogram on the https://jwt.io/ website, it is decoding successfully but the order of the claim struct object is changing. I don't know what to do right now?
any suggestions much appreciate
Note:- I need when we are going encode of the claim struct, that same struct need to decode with the same order.
for example, This is my claim struct with using private key, I am encoding the data
ClaimsRequest(
deviceId: "1D9B98D1-63FE-466B-99CB-A2CBDEB1612F",
amount: "32.00",
currency: "MUR",
debtorAccount: "1234567890",
creditorAccount: "255252522",
endToEndId: "CMCLMUM020220202000019",
consentId: "88379")
privateKey:
Printing description of privateKey:
"MIIEujANBgkqhkiG9w0BAQEFAAOCBKcAMIIEogIBAAKCAQEAotx6XajXdQFkn4LmqLhYgU0PVksLUc5X0eHpPicGoSsL7LtEY3Cp8x8iCZxdo0dxB+AUfl+deklS7alRkjgc5bp8Z2NCe5fNX4zeS2XVsk7W5wYQmUc2xnrX2yyTq81rnQ32SXppWEU/iGsUbWRTBaJYFxjIGM+qjcGnIHK9dvXkiN075uXyT8jVJOAbPUTSrtI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3wa1HNX9z6ZQi4c8rH38JCsL9tiY+XdtCsYim0dttJM6h/6P1QPYLbo2AYdtkPC9ONnXrvHHl1eIME5TAICsOOU0iuuFqGISKuWB/fheogwENfFdM1XK6A1ednBAoGAGIqs9UdlLVtOPqT1EIxceyH3JpncIsFeh7jcIYu6aGI1KqaNz094Ex88p9q5dylqE6iblq+n4EIyvB6MvCTGH2iYBU5M7GAlSWqGbNloFFMB7nSlzPOfKu6bwWSNn7S+ywx9gXx3IMpB/zxpFupaccuNn1A0Bk2E8kBYqooPNRw="
var myJWT = JWT(claims: myClaims)
do {
if let privateKeyData = Data(base64Encoded: privateKey) {
let jwtSigner = JWTSigner.rs512(privateKey: privateKeyData)
let signedJWT = try myJWT.sign(using: jwtSigner)
return signedJWT
}
}
it is given cryptogram of the data
Printing description of cryptogram:
▿ Optional
some : "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzUxMiJ9.eyJhbW91bnQiOiIzMi4wMCIsImRldmljZUlkIjoiMUQ5Qjk4RDEtNjNGRS00NjZCLTk5Q0ItQTJDQkRFQjE2MTJGIiwiY3JlZGl0b3JBY2NvdW50IjoiMjU1MjUyNTIyIiwiZW5kVG9FbmRJZCI6IkNNQ0xNVU0wMjAyMjAyMDIwMDAwMTkiLCJkZWJ0b3JBY2NvdW50IjoiMTIzNDU2Nzg5MCIsImN1cnJlbmN5IjoiTVVSIiwiY29uc2VudElkIjoiODgzNzkifQ.gjI_il7eu_topH2-i_UY_vFrD3rGpMe5a8R-mbO48MbKYaVcIJuNO4QxaqBR-nltBn5fPnZfWqxta6jqFJ4-W1CDIIVTDNI6vGZn8UTgn8TkZ21VA1wNb0Os067dGrDHtzlvJwrwOhLD2cND5F_YbN7v_cYMJEkTDKgTyi6w4HW3jqZPzMfEMfjQ36jlM8KlCf1_XeZ1V-OzNOmBhc6ToErHYJbM61fmV2DjVShGVqZ2dFu1Myw1FpaVvbp8YTA6_POq1kk3p8Ml6s6o0SQ3-c4cZ6f08z16fGGO7K-Tn7fDenZgX8oRQ0YvV3LeGzbbYgGFaqES_7KK1txLPOqTww"
So, when I paste this cryptogram in JWT.io it gives decoding Object, here you can see order changing of claim struct.
{
"amount": "32.00",
"deviceId": "1D9B98D1-63FE-466B-99CB-A2CBDEB1612F",
"creditorAccount": "255252522",
"endToEndId": "CMCLMUM020220202000019",
"debtorAccount": "1234567890",
"currency": "MUR",
"consentId": "88379"
}

json array parse return nil in swift 5

I have an json. In json there is multiple array. Here is my json...
["city": imrankhan136260#gmail.com,
"geofence_DEMRAhighway": {"type": "Polygon",
"coordinates":[[[90.45232332650568,23.714463300877014],[90.4532990923671,23.712264209703946],[90.45997933551394,23.714532021878767]]]}]
I have use bellow code get data ,it returns correct value
let city = myjson?["city"] as? String
print("city-->",city) // it returns imrankhan136260#gmail.com
But when it use bellow code get from geofence_DEMRAhighway key which returns nil. here is my code to get array
let geofence_BABUBAZARbridge = myjson?["geofence_BABUBAZARbridge"] as? [String: Any]
What is the wrong with the code. please help me to parse the json
This json is not filly correct.
It's starts from "[", but usualy {...} uses to map it to asociative array.
But if it works, you can still use it.
So, coordinates is not a string. You have to escape it, and it will see as
{\"type\": \"Polygon\",\r\n\"coordinates\":[[[90.45232332650568,23.714463300877014],[90.4532990923671,23.712264209703946],[90.45997933551394,23.714532021878767]]]}
If you can not change the format, then you shoud read it as JSonObject and convert it to string:
JSONSerialization.jsonObject(.....)
And then use
myjson?["city"]["type"]
You can try this:
JSONSerialization.data(withJSONObject: myjson?["city"], options: [])
myjson?["city"] will return an object, and JSONSerialization.data will convert it to string
And so one.

Send Core Data object to post api Alamofire multipartFormData

I have a screen on my app that I get some fields and save on my object Order. This object is my Core Data Object. After saving it, I need to send it to my backend through Alamofire POST multipartFormData.
The problem is that this is a Core Data Object (not Codable) and I need to send Data type on multipartFormData. How can I convert my object to Data? Is there another way of doing it?
What I've done:
let order = Order(context: DatabaseController.getContext())
order.orderItem = orderItem
order.product = product
order.value = value
order.date = date
Alamofire part:
Alamofire.upload (
multipartFormData: { multipartFormData in
multipartFormData.append(order, withName: "order")
},
to: url,
headers: headers,
encodingCompletion: { encodingResult in
The problem is how to put my object Order inside multipartFormData?
Could anyone help me please?
Updated:
Ok, sending the whole object didn't work, my api didn't accept, so I made a specific json only with the fields needed and turned it a Data type:
(PS: files are Data type from images user choose, even from camera or gallery)
var files = Dictionary<Data, String>()
var jsonFiles = [[String: String]]()
var jsonOrder = [String: Any]()
for file in files {
let dict : [String: String] = [ "orderImageIdLocal": uuidOrderImageIdLocal,
"orderItemAnalysisIdLocal": uuidAnalysisIdLocal,
"urlImageLocal": "\(imageId).jpg"]
jsonFiles.append(dict)
}
jsonOrder = [ "reason": "\(textViewReason)",
"orderImagess": jsonFiles,
"orderAnalysisId": "",
"orderIdLocal": "\(uuidAnaliseIdLocal)",
"orderId": "\(orderId ?? "")",
"typeSolicitation": "\(typeSolicitation)"]
Then I convert it to Data type like you said and send to Alamofire like above:
let orderData = try? JSONSerialization.data(withJSONObject: jsonOrder, options: .prettyPrinted) {
My problem now is that my api expect a zip file with those images user took from camera or gallery. So I am trying to use ZIPFoundation. I still don't know how to zip it and send. Should I zip each picture as Data type? Then transform zip file into Data type so I can send through multipartFormData.append?
I have tried: here and here
Here the code as an extension of NSManagedObject which creates dictionary from the attributes name.
extension NSManagedObject {
func toData() -> Data? {
let keys = Array(self.entity.attributesByName.keys)
let dict = self.dictionaryWithValues(forKeys: keys)
do {
let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
return jsonData
}
catch{}
return nil
}
}
Usage:
let jsonData = order.toData()
multipartFormData.append(jsonData, withName: "order")

Swift Convert XML to JSON

Is it possible to get a JSON var from XML on swift?
I already get xml values with alamofire and SWXMLHash with the below code, but requirements said I must convert it to JSON, is there a way to achieve this?
Alamofire.request(strURL, parameters: nil)
.responseData { response in
let xml = SWXMLHash.parse(response.result.value!)
if let text=xml["NewDataSet"]["Table"][0]["Book"].element?.text{
print(text)
}
}

Send base 64 string with alomofire

I trying to send post request with dictionary, one of its value is base64 string. So, I have parameters dict as follows:
let paramsDict : [String : Any] = [ "image" : self.avatarBase64String]
When I send a request, I got following in console:
FAILURE:
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
My base64 string is correct (quite lot of symbols though), but I did check it online and got an image from output.
Why I got such an error?
Please check your network connection.
Then you convert the imageView into Data and then convert into base64
Hope this code will help you:-
let pic = UIImageJPEGRepresentation(cameraView.image, 0.5)
let avatarBase64String = pic.base64EncodedString()
Here is what I have been using in order to make easy Dictionary representation of your parameters in order to make a POST request with Alamofire.
You can use this in your model class:
var dictionaryRepresentation: [String: Any] {
return [
"name" : self.name,
"title" : self.title,
"avatar" : self.avatar,
"age" : self.age,
]
}
You can remove the self if you are in your model class, it is just for a better understanding.
And then when you want to make your POST request, you can call it this way :
Imagine you have a class User, with attribute name, title, avatar and age as previously shown.
And you want to send your object User to your backend.
Here is how you can send your parameters as dictionary represented :
let user = User(name: name, title: title, avatar: avatar; age: age)
CustomService.shared.post(parameters: user.dictionaryRepresentation) { response in
// Handle response here
}
I strongly recommend you to abstract in a shared Service class all the networking methods.