Alamofire/Swift - How to add a boolean header value in request - ios

I want to create a request in Alamofire with headers with boolean values, but the HTTPHeaders just accept a dictionary [String:String].
What do I do?
Example of header that what I need:
static let headers: HTTPHeaders = [
"Content-Type":"application/json",
"boolValue": true
]

To response this,
I create a HTTPHeaders [String:String] like this:
static let headers: HTTPHeaders = [
"Content-Type":"application/json",
"boolValue": "true"
]
I changed my Alamofire request encoder from URLEncoding.default to JSONEncoding.default like this:
let req = Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: header)
This happens because Alamofire on URLEnconding no convert the dictionary [String:String] to primitive values and JSONEncoding does.

Related

Empty request body in swift

I'm having issues sending a post request to my api.
Both my iphone and my computer are on the same network, so I access the api the local public ip
In my app I set the App transport security to allow arbitrary urls.
The issue is the body is always empty.
I tried creating a localtunnel so I can access it via https but the body is till empty.
Here is my call
import UIKit
import Alamofire
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let parameters: Parameters = [
"foo": "bar",
"baz": ["a", 1],
"qux": [
"x": 1,
"y": 2,
"z": 3
]
]
let headers: HTTPHeaders = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request("my-url", method: .post, parameters: parameters, headers: headers ).responseJSON { (response) in
debugPrint(response.result)
}
}
}
Any idea how to fix this?
How exactly are you retrieving params in your api?
If from the request body (i.e. not form the query string) then you should also pass the encoding argument to your Alamofire's request function as well with JSONEncoding.default value because by default the encoding is URLEncoding.default which means that parameters will be passed as query string.
So change this:
Alamofire.request("my-url", method: .post, parameters: parameters, headers: headers).responseJSON { (response) in
debugPrint(response.result)
}
To:
Alamofire.request("my-url", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
debugPrint(response.result)
}
From Alamofire's doc
/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`,
/// `method`, `parameters`, `encoding` and `headers`.
///
/// - parameter url: The URL.
/// - parameter method: The HTTP method. `.get` by default.
/// - parameter parameters: The parameters. `nil` by default.
/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
/// - parameter headers: The HTTP headers. `nil` by default.
///
/// - returns: The created `DataRequest`.
#discardableResult
public func request(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil)
-> DataRequest
{
return SessionManager.default.request(
url,
method: method,
parameters: parameters,
encoding: encoding,
headers: headers
)
}

Swift 3 Alamofire print JSON body send to server

I use Alamofire to send requests in my iOS App. For debugging, i want to see what the JSON Body looks like in raw. I expect it to look like:
{"receiverUserGroups":["testgroup"],"message":"testmessage"}
But I have not found a way to print it out in that format. I simply define the header and the params and make a request.
let headers: HTTPHeaders = [
"sid": sid,
"Content-Type": "application/json"
]
var params = [
"receiverUserGroups":[""],
"message": "testmessage"] as [String : Any]
params["receiverUserGroups"] = group
Alamofire.request(urlString, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers)
Is there a way to see what i am sending to the server? Thank you in advance!

Pass parameter with json field when invoking POST in Alamofire

I have encountered an issue in swift 3:
I have an API which I need to access for data in my app, but the parameter that it demands is in the following format:
"jsonRequest" = {
"header" : "GetLocationListReq",
"accessKey" : "1234567890abcdefghij"
}//this is in json format.
I tried to pass this parameter as dictionary to call the API, but at that point I obtained this message error:
Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed
Any one knows how I can solve the problem?
I think you want to pass these things in header of the request.
for that you need to do like this
let headers = ["header": "GetLocationListReq",
"accessKey": "1234567890abcdefghij"]
Alamofire.request(url, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON{
r in
//do what you want here
}
hope this will work.
try to post this code
let par:[String:Any] = ["jsonRequest":[
"header" : "GetLocationListReq",
"accessKey" : "1234567890abcdefghij"
]]
pass it like that in Alamofire
Alamofire.request(url, method: .post, parameters: par, encoding: JSONEncoding.default, headers: nil).responseJSON{
r in
//do what you want here
}

Alamofire 4.3 can't send JSON request

Iam Trying to send a JSON request using Alamofire but it's not working as a JSON Request here's my JSON :
{"ClientID":"55050","AdminId":"myemail","Password":"123"}
content-type → application/json; charset=utf-8
and here's my code :
import Alamofire
func doLogin(username:String ,password:String) {
let parameters = ["ClientID":"55050" , "AdminId":username,"Password":password]
Alamofire.request("myurl.com", method: .post, parameters: parameters, encoding: JSONEncoding(options: []) ).responseJSON(completionHandler: {
response in
print(response)
})
and here's the response which i am getting
FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 3." UserInfo={NSDebugDescription=Invalid value around character 3.}))
By reading the documentation i just need to put header to set the request as application/json
so i added extra parameter header :
let headers: HTTPHeaders = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request(ApiKeys().login, method : .post , parameters : parameters, encoding: JSONEncoding.default , headers: headers).responseJSON { response in
}
and now it's working perfectly thanks everyone for trying to help :)
It seems you must have missed header in your request. So, there has been no response.
Your header must be a dictionary [String: String].
let header = ["Content-Type" : "application/json"]
And your sample request should be:
Alamofire.request(getCategoryPath, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: header)
.responseJSON { response in
guard response.result.error == nil else {
print(response.result.error!)
}
print(response.result.value)
}

post application/x-www-form-urlencoded Alamofire

I want to use Alamofire to retrieve a bearer token from Web API but I am new to ios and alamofire. How can I accomplish this with Alamofire?
func executeURLEncodedRequest(url: URL, model: [String : String]?, handler: RequestHandlerProtocol) {
addAuthorizationHeader()
Alamofire.request(.POST,createUrl(url), parameters: model, headers: headers,encoding:.Json)
}
Well you don't really need Alamofire to do this (it can be simply done using a plain NSURLRequest) but here goes:
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
let parameters = [
"myParameter": "value"
]
let url = NSURL(string: "https://something.com")!
Alamofire.request(.POST, url, parameters: parameters, headers: headers, encoding: .URLEncodedInURL).response { request, response, data, error in
print(request)
print(response)
print(data)
print(error)
}
I think that the headers can be omitted since alamofire will append the appropriate Content-Type header. Let me know if it works.
You can also find a ton of specification with examples here.
Alamofire 4.7.3 and Swift 4.0 above
As per the documentation for POST Request With URL-Encoded Parameters
let parameters: Parameters = [
"foo": "bar",
"val": 1
]
// All three of these calls are equivalent
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.default)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)
// HTTP body: foo=bar&val=1
Alamofire 5.2
let parameters: [String: [String]] = [
"foo": ["bar"],
"baz": ["a", "b"],
"qux": ["x", "y", "z"]
]
// All three of these calls are equivalent
AF.request("https://httpbin.org/post", method: .post, parameters: parameters)
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder.default)
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder(destination: .httpBody))
// HTTP body: "qux[]=x&qux[]=y&qux[]=z&baz[]=a&baz[]=b&foo[]=bar"
Here is example code that should work with Alamofire 4.x and Swift 3.x as of August 2017:
let parameters = [
"myParameter": "value"
]
Alamofire.request("https://something.com", method: .post, parameters: parameters, encoding: URLEncoding()).response { response in
print(response.request)
print(response.response)
print(response.data)
print(response.error)
}
There is no need to set the content-type header explicitly, as it is set by Alamofire automatically.

Resources