Is Possible to POST array of dictionaries in Afnetworking POST Method? - ios

I am developing one iOS application that Post data to web service and Get data from the Web service.
I am using Afnetworking for Post the data to web service.Web service accept the data in the form of array of dictionaries like
[{"name":"stephen","age":25},{"name":"john","age":35},{"name":"david","age":45},{"name":"roger","age":15}]
which need to send in the body of the request and set Accept application/json in the header of the request.
I checked some examples already avilable in the stack overflow but all are explain about Post dictionary .My question is possible to Post array to web service using Afnetworking. If it is possible help me to develop the code which completely reach my requirements.

If your are sending all dictionaries in single array. Very first you have to JSONserialize every dictionary and then put it in array and then again JSON serialise the whole array. Then only it will be called as a correct JSON format. Its the only way you can do it.

My suggestion for you is to use AFJSONRequestSerializer.
Swift solution:
let manager = AFHTTPSessionManager(baseURL: URL(string: yourBaseURL))
manager.requestSerializer = AFJSONRequestSerializer()
let parameters: [[String: Any]] = [["name": "stephen", "age": 25], ["name": "john", "age": 35],["name": "david", "age": 45]]
manager.post(requestURL,
parameters: parameters,
progress: nil,
success: { (task, data) in
// process server response
}, failure: { (task, error) in
// process error server response
})
AFJSONRequestSerializer sets Content-type to application/json in request header.

Related

Is there any way to pass response object values from first request to second request as input parameters in graph batch request

Is there any way to pass response object values from first request to second request as input parameters in graph batch request (2nd request is dependant on 1st request - graph/json-batching)
In the following request, the client is specifying that requests 1 should be run first, then request 2.
2nd Request need the id from the 1st Request's response as URL variable. What is the way to achieve it?
JSON
{
"requests": [
{
"id": "1",
"method": "GET",
"url": "/users/<upn>?$select=id"
},
{
"id": "2",
"dependsOn": [ "1" ],
"method": "GET",
"URL": "users/<id from the 1st request>/presence"
}
]
}
Yes, As #Tiny-wa said this is not possible as of now. There is already a feature request raised in the Microsoft Graph Feedback Forum, please upvote it so that the product team may implement it in future.
So, for now you need to make two separate requests, make first request and get response details and use it and make a second request.

Updating stars in Firebase post by transaction

According to the Firebase documentation, it is recommended to duplicate the store data for faster access like so (Firebase example):
let key = ref.child("posts").childByAutoId().key
let post = ["uid": userID,
"author": username,
"title": title,
"body": body]
let childUpdates = ["/posts/\(key)": post,
"/user-posts/\(userID)/\(key)/": post]
ref.updateChildValues(childUpdates)
And, afterwords if you want to add a rating/stars to the post, you should do it with a runTransactionBlock call to a reference:
ref.runTransactionBlock({ (currentData: FIRMutableData) -> FIRTransactionResult in {}
The reference to this last call is the reference to the post you wanna rate
My question is, How are we suppose to update two different references in the same transaction?
Should we make 2 of them? It doesn't seem really safe to me to do it this way
Thank you for your help

In Swift, How to have a json request automatically cancel itself if the data returned is of a different format?

I'm running into this problem where JSON data downloaded from a site is of a different format compared to other data received from the same site. This problem is causing the app to freeze. For example 98% percent of the data received from the site looks like this:
{
id: 27673,
title: "Unbreakable Kimmy Schmidt",
alternate_titles: [ ],
status: "",
type: "online",
container_show: 0,
first_aired: "2015-02-17",
network: ""
}
but for some strange reason some of the JSON data is formatted like this:
{
id: 35107,
title: "Jessica Jones",
alternate_titles: [ ],
status: "",
type: "online",
container_show: 0,
first_aired: false,
network: ""
}
The value for "first_aired" is a string for the first JSON data but a Bool for the second. Is there to make the JSON data automatically cancel the request if the format of the JSON data changes and go back to the original view it was on before the request was made? Or even better just skip over the value that is different than the original format but still retrieve the rest of the data?
Caleb's method worked. I removed the optional binding from all the JSON data and instead have it set up like this:
let firstAired = jsonResult["first_aired"] as? String ?? "N/A"
It worked like a charm. The app doesn't freeze anymore and when the JSON data is of a different format it reads "N/A" instead.

AFNetworking 2.0 sends parameters and image to server

I am using AFNetworking2 to send parameters and image to server.
manager.POST(urlPath, parameters: parameters, constructingBodyWithBlock: { (formData: AFMultipartFormData!) -> Void in
formData.appendPartWithFileData(imageData!, name: "image", fileName: "dummy.jpg", mimeType: "image/jpeg")
}, success: { (dataTask: NSURLSessionDataTask!, responseObject: AnyObject!) -> Void in
println("success: \(responseObject.description)")
}, failure: { (dataTask: NSURLSessionDataTask!, error: NSError!) -> Void in
println("failure: \(error)")
})
On server side, the data will be a dictionary merged by parameters(QueryDict) and the image data(MultiValueDict):
data=MergeDict(<QueryDict: {u'owner': [u'6'], u'description': [u'this
is p1'], u'name': [u'p1']}>, <MultiValueDict: {u'image':
[<InMemoryUploadedFile: file.jpg (image/jpeg)>]}>)
I reckon the 'MultiValueDict' is from this part of code:
formData.appendPartWithFileData(imageData!, name: "image", fileName: "dummy.jpg", mimeType: "image/jpeg")
However, I wanted to have MultiValueDict like this:
{u'groupImages': [{u'image': [<InMemoryUploadedFile: file.jpg (image/jpeg)>]}]}
The data format is a Dictionary with an array value, and the array has another Dictionary value.
So what can I do to make formData.appendPartWithFileData become such above data format?
EDIT:
I have seen some posts similar to my question.
For example this one: AFNetworking post image in nested json
I have tried to change my code like this:
formData.appendPartWithFileData(imageData!, name: "groupImages[0].image", fileName: "dummy.jpg", mimeType: "image/jpeg")
or
formData.appendPartWithFileData(imageData!, name: "groupImages[0][image]", fileName: "dummy.jpg", mimeType: "image/jpeg")
but none of them worked for me.
My server expects to receive a JSON like this:
{
"name": "p2",
"owner": 6,
"description": "this is p2",
"groupImages": [{
"image": <InMemoryUploadedFile: dummy.jpg (image/jpeg)>
}]
}
Any idea?
When you send a multipart HTTP request, the JSON data and the image data are separate - literally in multiple parts. It might be worth taking a look at this answer to "What is HTTP Multipart Request" so you can see how the data is transmitted.
The long and short of it is that the JSON and the image are merged into a dictionary on the server end. The image is not transmitted embedded within the JSON. The semantics of how they're merged (for example, how a name like groupImages[0][image] is used to merge in with the JSON dictionary) are determined by the server, not by your iOS app.
So, your server team should be able to specify how you name this file so that it's merged with the dictionary correctly. They should be able to produce a sample HTTP request that works properly (for example, using curl or Postman). If your server has a web app, you could inspect the analogous function in the web app to see what the request looks like there. Once you have a working request, you can mimic it by comparing your outgoing NSURLRequest to the sample request they provide.

POST request to test Rails API using

I am new to programming with Rails API.
To test my Rails API, I need to build a manual POST request with data format like
{
"user":
{
"email": "abc#gmail.com",
"name": "abc",
}
}
I am trying to use Simple REST Client but not able to get the URL with data in the above format. How do I write the URL to get the data in the right format?

Resources