Send empty array with Alamofire API Rest - json

I want to send an empty array to a Rest Full API by using patch method. But i don't know why it is not working. In fact, i am also using postman for testing my requests, and this request works fine in postman ( I want wordTrads be empty ) :
And this is how i've implemented that API called in Swift by using Alamofire :
let parameters = [
"wordTrads" : [],
]
Alamofire.request("\(Auth.URL_API)/lists/205",method: .patch, parameters : parameters).responseJSON { (response) in
print("List patched")
}
But in swift it's not working like if Alamofire doesn't send empty arrays.
I am using Alamofire 4.6.0 and Swift 4.

Your screen snapshots suggest you're expecting to send JSON, but your Alamofire syntax is not doing that. You need to add encoding of JSONEncoding.default if you want to send JSON:
let parameters = [
"wordTrads" : []
]
Alamofire.request("\(Auth.URL_API)/lists/205", method: .patch, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result {
case .success(let value): print(value)
case .failure(let error): print(error)
}
}
And if you do that, the body of the request includes that empty array in JSON form:
{"wordTrads":[]}

Related

back4App, query using alamofire

I'm trying to make a query request on my database in back4app using Alamofire.
(i don't want to use Parse, for study purpose).
My DB has 2 simple field , Name and Age
I would like to send .get request using AF to obtain the data relative to a specific name.
I'm able to retrive all data in the DB with the following function:
func readData(){
AF.request(url!, method: .get, headers: headers).responseJSON { json in
print(json)
}
}
as per the back4app documentation in order to query a specific field is reported:
" specified the Parameters where URL parameter constraining the value for keys. It should be encoded JSON"
here my test:
func readDataQuery(name: String){
let param: [String: String] = [
"Name": name
]
AF.request(url!, method: .get, parameters: param, headers: headers)
.responseJSON { json in
print(json)
}
}
but it return an error:
success({
code = 102;
error = "Invalid parameter for query: Name";
})
how can I write the parameters to pass at the request?
thanks
You are getting this error because there is no such query parameter called "Name". In order to get objects via a condition, you would have to use the "where" clause like this.
let param: [String: String] = ["where": "{"Name":"Meimi"}"]
For more information please visit this website
https://docs.parseplatform.org/rest/guide/#query-constraints

How to detect when Alamofire request is null?

I am using Alamofire to do my requests of my API on my Swift application and it works well but I also want to detect when the JSON response is equals to null.
I have tried comparing the response to nil and NSNull but none of those worked for me. I also have tried using JSON.empty but it also does not seem to work. Further, I have created a default option on my switch application trying to catch the options that are not success or failure.
Actually I have only maintained the JSON.empty option but it never enters on else statement.
This is the code that I have right now:
Alamofire.request(encodedUrl!, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { response in
switch(response.result) {
case .success(_):
if let JSON = response.result.value as? [[String : AnyObject]]{
if JSON.isEmpty == false{
//Here the code if the request returns data
}else{
//Here I wanted to use the code if null is retrieved
}
}else{
//The JSON cannot be converted
}
break
case .failure(_):
//Failure
break
}
}
How can I handle null responses on Alamofire?
Thanks in advance!
According to you code, it'll hit the // The JSON cannot be converted since null can't be casted to [[String: AnyObject]].

Alamofire Swift get html source

I just want to retrieve the html source from a simple website.
#IBAction func scan_func(sender: AnyObject) {
Alamofire.request(.GET, "http://www.example.com")
.response { request, response, data, error in
print(request)
print(response)
print(data)
}
}
I already have successfully added "App Transport Security Settings" and "Allow Arbitrary Loads" to info.plist to load http content.
When I run that code I only get an output like this:
XCODE - hexadecimal output
I hope you can help me.
kind regards
You are printing out the raw bytes of the data. I'm guessing you are looking for a way to print out the corresponding string representation.
You could for instance do this with Alamofire's provided closure:
Alamofire.request(.GET, "http://www.example.com")
.responseString { response in
print("Response String: \(response.result.value)")
}
(Check out the documentation here)
Alternatively, you could convert the string yourself:
Alamofire.request(.GET, "http://www.example.com")
.response { request, response, data, error in
print(String(data: data, encoding: String.Encoding.utf8))
}
Apple String reference documentation

How to debug network request Swift

I'm making a http request to an API with JSON in the body of the request. I know for a fact that my Dictionary<String, String> containing the JSON data is correct, still I'm getting a response from the server that my input data is not valid. I'm doing something very similar to this: Swift 2.0 url post request. I even tried the extension suggested there but without success.
how should I debug this? I can't find any way to print my whole request to the console. I want to know what my URLRequest actually contains just before I send the request. Also, I want to know that this hex gibberish is actually the right gibberish I meant it to be, how should I do this?
Nothing special about that? Just write an extension and print whatever you want
example:
extension Data {
func toString() -> String? {
return String(data: self, encoding: .utf8)
}
}
extension URLRequest {
func log() {
print("\(httpMethod ?? "") \(self)")
print("BODY \n \(httpBody?.toString())")
print("HEADERS \n \(allHTTPHeaderFields)")
}
}
Usage:
request.log()
Sample log:
POST https://httpbin.org/
BODY
Optional("password=xxx&username=xxx")
HEADERS
Optional(["Content-Type": "application/x-www-form-urlencoded; charset=utf-8"])

HTTPTask response into Swifty for JSON serialization

I'm using HTTPTask to load data from openweathermap.org. Which is working fine. I'm having trouble converting the data to JSON. I'd like to use SwiftyJSON but, I can't quite figure out how to bridge the two.
HTTPTask has a JSON Serializer, which I got working, but I rather use Swifty, it's seems easier to work with.
Here's what I have so far. This loads the weather from openweathermap.org. I'm not sure how to pass the response into Swifty.
var request = HTTPTask()
request.requestSerializer = JSONRequestSerializer()
request.responseSerializer = JSONResponseSerializer()
request.GET(openWeatherURL, parameters: ["q":"San Francisco", "APPID":openWeatherAPIKey], success: {(response: HTTPResponse) in
if let dict = response.responseObject as? Dictionary<String, AnyObject> {
println("Response: \(response)")
println("Dictionary: \(dict)")
let description = dict["weather"]["description"]
println(description)
}
}, failure: {(error: NSError, repsonse: HTTPResponse?) in
println("error \(error)")
})
SwiftyJSON is quite happy to take a variety of objects, including Dictionary?, so just go for it!
let dict = JSON(response.responseObject)