I'm trying to figure out how to use Alamofire with a JSONAPI datasource. I'm trying to POST
some data. The code below doesn't work. I'm learning HTTP requests and JSON as I go, so there might be other issues with the code. Would really appreciate any help.
let parameters = [
"data" : [
"type" : "notes",
"attributes" : [
"relevant-date" : date,
"details" : self.textField.text
],
"relationships" : [
"child" : [
"data" : [
"type" : "children",
"id" : self.passedChildID!
]
]
]
]
]
Alamofire.request(.POST, "url", parameters: parameters, encoding: .JSON)
.responseJSON { (response) -> Void in
if let value = response.result.value {
let json = JSON(value)
}
}
This was solved with a server side filter and the updated code is as follows.
let parameters = [
"auth_token" : "test",
"filter" : [
"phone-number" : self.PhoneNumber!
]
]
Alamofire.request(.GET, url, parameters: parameters, encoding: .URL)
.responseJSON { (response) -> Void in
print("Request \(response.request)")
}
EDIT
I really solved it with code from the Alamofire Github page. I had to add the 2 separate headers that are identified below.
let URL = NSURL(string: "https://httpbin.org/post")!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.HTTPMethod = "POST"
let parameters = ["foo": "bar"]
do {mutableURLRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions())
} catch {
// No-op
}
mutableURLRequest.setValue("application/vnd.api+json", forHTTPHeaderField: "Content-Type") //one header
mutableURLRequest.setValue("application/vnd.api+json", forHTTPHeaderField: "Accept") //second header
Alamofire.request(mutableURLRequest)