I'm using Alamofire for my Rest (POST) request and getting JSON response seamlessly. But i can access only response body. I want to get response headers. Isn't it possible when using Alamofire?
Here is my code snippet:
#IBAction func loginButtonPressed(sender: UIButton) {
let baseUrl = Globals.ApiConstants.baseUrl
let endPoint = Globals.ApiConstants.EndPoints.authorize
let parameters = [
"apikey": "api_key_is_here",
"apipass": "api_pass_is_here",
"agent": "agent_is_here"
]
Alamofire.request(.POST, baseUrl + endPoint, parameters: parameters).responseJSON {
(request, response, data, error) in let json = JSON(data!)
if let result = json["result"].bool {
self.lblResult.text = "result: \(result)"
}
}
}
As response is of NSHTTPURLResponse type, you should be able to get the headers as followed:
response.allHeaderFields
Here is how to access the response headers in Swift 3:
Alamofire.request(.GET, requestUrl, parameters:parameters, headers: headers)
.responseJSON { response in
if let headers = response.response?.allHeaderFields as? [String: String]{
let header = headers["token"]
// ...
}
}
This code gets response header in Swift 4.2
Alamofire.request(pageUrlStr, method: .post, parameters: Parameter, encoding: URLEncoding.httpBody, headers: nil).responseJSON
{ response in
//to get JSON return value
if let ALLheader = response.response?.allHeaderFields {
if let header = ALLheader as? [String : Any] {
if let cookies = header["Set-Cookie"] as? String {
UserDefaults.standard.set(cookies, forKey: "Cookie")
}
}
}
}
Related
I am trying to send POST HTTP request with body using Alamofire and would appreciate any help.
My body:
{"data":{"gym":{"country":"USA","city":"San Diego","id":1}}}
Should I do something like this?
let parameters: [String: Any] = [ "data": [
"gym": [
"country":"USA",
"city":"San Diego",
"id":1
]]]
Alamofire.request(URL, method: .post, parameters: parameters, headers: headers())
.responseJSON { response in
print(response)
}
If you wish to send the parameters in json format use encoding as JSONEncoding. So add parameter for encoding in request as follows:
Alamofire.request(URL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers())
.responseJSON { response in
print(response)
}
Hope it helps...
Try this method to convert your json string to dictionary
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
let str = "{\"data\":{\"gym\":{\"country\":\"USA\",\"city\":\"San Diego\",\"id\":1}}}"
let dict = convertToDictionary(text: str)
and send dictionary as a param in your request.
Alamofire.request(URL, method: .post, parameters: dict, headers: headers())
.responseJSON { response in
print(response)
}
ref : How to convert a JSON string to a dictionary?
What I think is that you should try and prepare your dictionary in the this format:
var gym = [String:Any]()
gym["country"] = "USA"
gym["city"] = "San"
var data = [[String:Any]]()
data.append(gym)
var metaData = [String:Any]()
metaData["data"] = data
Your parameters is wrong...
let parameters: [String: Any] = { "data":
{
"gym": {
"country":"USA",
"city":"San Diego",
"id":1
}
}
}
Alamofire.request(<YOUR-URL>,
method: .post,
parameters: parameters,
encoding: URLEncoding(destination: .queryString),
headers: <YOUR-HEADER>
).validate().responseString { response in
switch response.result {
case .success:
debugPrint("Good to go.")
debugPrint(response)
case .failure:
let errMsg = String(data: response.data!, encoding: String.Encoding.utf8)!
debugPrint(errMsg)
debugPrint(response)
}
}
Hope this help. BTW, in Alamofire 5, debugPrint(response) can print out response.data directly.
You can use the httpBody property of URLRequest along with Alamofire Session request:
var req = try? URLRequest(url: url, method: method, headers: headers)
req?.httpBody = someJson
Alamofire.Session(configuration: .default).request(req!).validate().response { response in
// Handle the response
}
I have to parse json using alamofire
before am using json session its working fine getting data from the json. now am try to parse json using alamofire.
this is the code parse the json using json, this code working fine
func auth(_ email:String,password:String) {
var request = URLRequest(url:AppConstants.apiURLWithPathComponents("usersignin"))
let session = URLSession.shared
request.httpMethod = "POST"
let bodyData = "email=\(email)&passCode=\(password)&deviceType=iOS&deviceId=\(deviceToken)"
request.httpBody = bodyData.data(using: String.Encoding.utf8);
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
do {
if data != nil {
if let jsonData = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary {
errorCode = String(describing: jsonData["errorCode"]!)
msg = jsonData["msg"] as! String
print(errorCode)
print(jsonData)
if(errorCode == "1"){
DispatchQueue.main.async(execute: {
self.activityIndicator.stopAnimating()
})
} else {
self.name = jsonData.value(forKey: "name") as! String
if let kidsURLDetails = jsonData["kidsURLDetails"] as? NSArray {
for i in 0 ..< kidsURLDetails.count {
if kidsURLDetails[i] is NSDictionary {
let url = kidsURLDetails[i] as? NSDictionary
self.urls.append((url?["url"]) as! String)
}
}
}
self.serverURL = self.urls.joined(separator: ",")
print("ServerURL \(self.serverURL)")
let prefs:UserDefaults = UserDefaults.standard
prefs.setValue(self.name, forKey: "NAME")
DispatchQueue.main.async(execute: {
UIApplication.shared.endIgnoringInteractionEvents()
let controllerId = "NavID"
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let initViewController: UIViewController = storyboard.instantiateViewController(withIdentifier: controllerId) as UIViewController
self.present(initViewController, animated: true, completion: nil)
})
}
}
} else {
}
} catch let err as NSError {
print("JSON Error \(err)")
}
})
task.resume()
}
in above code I used post method with passing parameters, when I am trying post method with parameter passing in almofire am getting error "Extra argument 'method' in call", username and password coming from textfield so after enter the email and password I have pass the parameters using post method.
this is the code I will implemented in to alamofire json parse
var request = URLRequest(url:AppConstants.apiURLWithPathComponents("usersignin"))
let bodyData = "email=\(username)&passCode=\(passcode)&deviceType=iOS&deviceId=123456"
let deviceId = "1234"
let params: [String: Any] = ["email": username, "passCode": passwordstring, "deviceType": "IOS","deviceId":deviceId]
Alamofire.request(request, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil)
.responseJSON { response in
print(response.result.value as Any) }
if I can try this code working
Alamofire.request("http://www.kids.com/rk/api/usersignin?email=demo#kidsapp.com&passCode=123456&deviceType=&deviceId=", method: .post, parameters: nil, encoding: JSONEncoding.default, headers: nil)
.responseJSON { response in
print(response.result.value as Any) }
how can I parse the json post method passing parameters using alamofire. where I did mistake pls help me
You are passing wrong type in 1 param in call it should be URLConvertible(string or URL) not URLRequest. try below code.
let params: [String: Any] = ["email": username, "passCode": passwordstring, "deviceType": "IOS","deviceId":deviceId]
let url = URL(string: "http://www.kids.com/rk/api/usersignin")!
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil)
.responseJSON { response in
}
____________Edit___________
here header is post request headers(if any) or nil
let params: [String: Any] = ["email": username, "passCode": passwordstring, "deviceType": "IOS","deviceId":deviceId]
let urlString = "http://www.kids.com/rk/api/usersignin"
guard let url = URL(string: urlString), var request = try? URLRequest(url: url, method: .post, headers: header) else{
//
return
}
request.httpBody = params.map{ "\($0)=\($1)" }.joined(separator: "&").data(using: .utf8)
Alamofire.request(request).responseJSON { response in
}
If you need to send the parameters in url with post request you should use URLEncoding.default encoding rather than JSONEncoding.default. JSONEncoding is used when you need to send JSON data as body with content type application/json.
Change your code like:
Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { response in
print(response.result.value as Any)
}
Or you can remove encoding parameter as URLEncoding is the default encoding of Alamofire.
// URL
let urlString = “URL_Here”
var params = [String: Any]()
//Contruct your params
params = ["email": username, "passCode": passwordstring, "deviceType": "IOS","deviceId":deviceId]
// Request
Alamofire.request(urlString, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.responseJSON { response in
if (response.result.error == nil) {
let value = response.result.value
print(value)
}
else {
let errorString = response.result.error
print(errorString)
}
}
I'm having a problem on using Alamofire. When I try to post a request using a generic parameters like ["name":"John", "age":"27"] it always succeeds. But, when I try to use a web service that requires parameters and a body-raw for a base64 string I'm not able to get a successful response from the server. Though it succeeds when I use Postman. Does anyone knows how to do this on Alamofire 4? Here is the screenshot of my postman.
Thank you!
#nathan- this is the code that I used. I just assumed that the base64String inside the "let paramsDict" has a key value named "data" though it doesn't have a key name in postman.
let urlString = ApiManager.sharedInstance.formsURL + ApiManager.sharedInstance.mobileFormsImageUpload
let paramsDict = ["token": token, "fileID":"2", "filename":"images.png", "data": base64String] as [String : Any]
Alamofire.request(urlString, method: .post, parameters: paramsDict, encoding: URLEncoding.httpBody, headers: [:])
.responseJSON{ response in
switch response.result {
case .success(let data):
debugPrint("SUCCESS")
case .failure(let error):
debugPrint("Request Error")
}
}
I already figured it out. It needs a custom encoding to make it work. All the parameters must be inlined with the url so the base64 string inside the parameter is the only to be encoded. Here is the code that I used.
struct CustomPostEncoding: ParameterEncoding {
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try URLEncoding().encode(urlRequest, with: parameters)
let base64 = parameters?["data"] as! String
let finalBase64Format = "\"" + base64 + "\""
let postData = NSData(data: finalBase64Format.data(using: String.Encoding.utf8)!)
request.httpBody = postData as Data
return request
}
}
func uploadImageBase64(){
let jpegCompressionQuality: CGFloat = 0.9 // Set this to whatever suits your purpose
if let base64String = UIImageJPEGRepresentation(testIMG, jpegCompressionQuality)?.base64EncodedString() {
var token = String()
if let data = UserDefaults.standard.data(forKey: "userProfile"),
let user = NSKeyedUnarchiver.unarchiveObject(with: data) as? UserProfile{
token = user.token
} else {
print("There is an issue")
}
let headers = [
"content-Type": "application/json"
]
let urlString = "http://localhost/FormsService.svc/Getbase64?filename=test.png&fileID=1151&token=80977580xxx"
let paramsDict = ["data": base64String] as [String : Any]
Alamofire.request(urlString, method: .post, parameters: paramsDict, encoding: CustomPostEncoding(), headers: headers)
.responseJSON{ response in
print("response JSON \(response.result)")
}
.response{ response in
print("RESPONSE \(response)")
}
}
}
I'm using Swift 3 and Alamofire 4.0.
I want to create similar Alamofire POST request as Postman request shown in screenshot:
I've tried with these lines of code:
var parameters: [String: Any] = [
"client_id" : "xxxxxx",
"client_secret" : "xxxxx",
"device_token" : "xxxx",
"fullname" : "xxxxx",
"gender": "xxx"
]
Alamofire.request(url, method: .post, parameters: parameters).responseJSON { response in
print(response)
}
But I got this error:
How to implement POST request with Body as form-data using Alamofire in Swift 3?
Swift 3.0 - Alamofire - Working code for multipart form data upload *
// Parameters
let params: [String : String] =
["UserId" : "\(userID)",
"FirstName" : firstNameTF.text!,
"LastName" : lastNameTF.text!,
"Email" : emailTF.text!
]
// And upload
Alamofire.upload(
multipartFormData: { multipartFormData in
for (key, value) in params
{
multipartFormData.append((value.data(using: .utf8))!, withName: key)
}
},
to: url,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
upload.uploadProgress(queue: DispatchQueue(label: "uploadQueue"), closure: { (progress) in
})
case .failure(let encodingError):
print(encodingError)
}
}
)
Let me know if you still have issues with it.
after too much try I have succeded so try this
override func viewDidLoad() {
super.viewDidLoad()
let parameters: Parameters = ["client_id": "1","user_token":"xxxxxxxx"]
// Do any additional setup after loading the view, typically from a nib.
let url = "http://xxxxxxxxxxx/index.php/Web_api/get_client_profile"
//let timeParameter = self.getLastTimeStamp()
self.request = Alamofire.request(url, method: .post, parameters:parameters)
if let request = request as? DataRequest {
request.responseString { response in
//PKHUD.sharedHUD.hide()
do{
let dictionary = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
print(dictionary)
}catch{
}
}
}
}
var request: Alamofire.Request? {
didSet {
//oldValue?.cancel()
}
}
You can post a request using Alamofire.
let url = ""
let headers = [ "Content-Type" : "application/json"]
let para : Parameters = [ "data" : JSONObject]
Alamofire.request(url, method: .post, parameters: para, encoding: JSONEncoding.default, headers : headers)
.responseJSON { response in
print(response)
print(response.result)
}
Nothing to worry about.
Alamofire request method not changed so much(For Swift 3.0) if in case you know how to do that in Swift 2.0/2.2. If you understand the old method then you can easily understand this one also. Now lets take a closer look on the following boilerplate -
Alamofire.request(apiToHit, method: .post, parameters: parametersObject, encoding: JSONEncoding.default, headers: headerForApi).responseJSON { response in switch response.result{
case .success(_):
if let receivedData: Any = response.result.value{
if let statusCode: Int = response.response?.statusCode {
//Got the status code and data. Do your data pursing task from here.
}
}else{
//Response data is not valid, So do some other calculations here
}
case .failure(_):
//Api request process failed. Check for errors here.
}
Now here in my case -
apiToHit //Your api url string
.post //Method of the request. You can change this method as per you need like .post, .get, .put, .delete etc.
parametersObject // Parameters needed for this particular api. Same in case you are sending the "body" on postman etc. Remember this parameters should be in form of [String: Any]. If you don't need this then you can just pass nil.
JSONEncoding.default //This the encoding process. In my case I am setting this as .default which is expected here. You can change this to .prettyPrinted also if you need.
headerForApi //This is the header which you want to send while you are requesting the api. In my case it is in [String: String] format. If you don't need this then you can just pass nil.
.responseJSON //Expecting the response as in JSON format. You can also change this as you need.
Now, in my request I am using Switch inside the request closure to check the result like response in switch response.result{.
Inside case .success(_): case I am also checking for result data and http status code as well like this
if let receivedData: Any = response.result.value{
if let statusCode: Int = response.response?.statusCode {
}
}
Hope this helped. Thanks.
class func alamofireMethod(methods: Alamofire.HTTPMethod , url : URLConvertible , parameters : [String : Any],need_flag_inside : Bool = false, paramJson : Bool = true ,need_loader : Bool = true,Header: [String: String],handler:#escaping CompletionHandler,errorhandler : #escaping ErrorHandler)
{
if NetworkController.sharedInstance.checkNetworkStatus()
{
var alamofireManager : Alamofire.SessionManager?
var hed = Header
if let tok = UserDefaults.standard.value(forKey: "TOKEN") as? String {
hed = ["Authorization":"Bearer \(tok)"]
}
if need_loader {
// DELEGATE.showLoader()
}
var UrlFinal = ""
do
{
try UrlFinal = baseURL + url.asURL().absoluteString
}
catch{}
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForResource = 25
configuration.timeoutIntervalForRequest = 25
configuration.httpAdditionalHeaders = hed
alamofireManager = Alamofire.SessionManager(configuration: configuration)
alamofireManager = Alamofire.SessionManager.default
let json = JSON(parameters)
guard let jsonDict = json.dictionaryObject else {
return
}
var jsonData = Data()
do {
jsonData = try JSONSerialization.data(withJSONObject: jsonDict, options: [])
} catch {
//handle error
print(error)
}
var request = URLRequest(url: URL(string: UrlFinal)!)
request.httpMethod = methods.rawValue
if methods == .post || methods == .put
{
//check here
if paramJson {
hed["Content-Type"] = "application/json"
request.httpBody = jsonData
}else{
let postString = self.getPostString(params: parameters)
request.httpBody = postString.data(using: .utf8)
}
}
request.allHTTPHeaderFields = hed
Alamofire.request(request).responseJSON(queue: nil, options: JSONSerialization.ReadingOptions.allowFragments) { (response) in
print(parameters)
print(UrlFinal)
print(hed)
// DELEGATE.hideLoader()
if response.result.isSuccess
{
print(response)
handler(response.result.value! as AnyObject)
}
else if response.response?.statusCode == 401
{
// DELEGATE.redirectToLogin()
// DELEGATE.showToast(message: "Token Expired")
}
else{
// DELEGATE.showToast(message: default_failure)
errorhandler(response.result.error! as NSError)
print(response.result.error as Any)
}
}
}else{
// DELEGATE.showToast(message: "Please check your internet connection.")
}
}
Alomofire With Post and Put Method In swift
how is it possible to send a POST request with a simple string in the HTTP body with Alamofire in my iOS app?
As default Alamofire needs parameters for a request:
Alamofire.request(.POST, "http://mywebsite.example/post-request", parameters: ["foo": "bar"])
These parameters contain key-value-pairs. But I don't want to send a request with a key-value string in the HTTP body.
I mean something like this:
Alamofire.request(.POST, "http://mywebsite.example/post-request", body: "myBodyString")
Your example Alamofire.request(.POST, "http://mywebsite.example/post-request", parameters: ["foo": "bar"]) already contains "foo=bar" string as its body.
But if you really want string with custom format. You can do this:
Alamofire.request(.POST, "http://mywebsite.example/post-request", parameters: [:], encoding: .Custom({
(convertible, params) in
var mutableRequest = convertible.URLRequest.copy() as NSMutableURLRequest
mutableRequest.HTTPBody = "myBodyString".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
return (mutableRequest, nil)
}))
Note: parameters should not be nil
UPDATE (Alamofire 4.0, Swift 3.0):
In Alamofire 4.0 API has changed. So for custom encoding we need value/object which conforms to ParameterEncoding protocol.
extension String: ParameterEncoding {
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try urlRequest.asURLRequest()
request.httpBody = data(using: .utf8, allowLossyConversion: false)
return request
}
}
Alamofire.request("http://mywebsite.example/post-request", method: .post, parameters: [:], encoding: "myBody", headers: [:])
You can do this:
I created a separated request Alamofire object.
Convert string to Data
Put in httpBody the data
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let pjson = attendences.toJSONString(prettyPrint: false)
let data = (pjson?.data(using: .utf8))! as Data
request.httpBody = data
Alamofire.request(request).responseJSON { (response) in
print(response)
}
If you use Alamofire, it is enough to set encoding type to URLEncoding.httpBody
With that, you can send your data as a string in the httpbody although you defined it as json in your code.
It worked for me..
Updated for Badr Filali's question:
var url = "http://..."
let _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
let params : Parameters = ["grant_type":"password","username":"mail","password":"pass"]
let url = NSURL(string:"url" as String)
request(url, method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: _headers).responseJSON(
completionHandler: { response in response
let jsonResponse = response.result.value as! NSDictionary
if jsonResponse["access_token"] != nil
{
access_token = String(describing: jsonResponse["accesstoken"]!)
}
})
I modified #Silmaril's answer to extend Alamofire's Manager.
This solution uses EVReflection to serialize an object directly:
//Extend Alamofire so it can do POSTs with a JSON body from passed object
extension Alamofire.Manager {
public class func request(
method: Alamofire.Method,
_ URLString: URLStringConvertible,
bodyObject: EVObject)
-> Request
{
return Manager.sharedInstance.request(
method,
URLString,
parameters: [:],
encoding: .Custom({ (convertible, params) in
let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
mutableRequest.HTTPBody = bodyObject.toJsonString().dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
return (mutableRequest, nil)
})
)
}
}
Then you can use it like this:
Alamofire.Manager.request(.POST, endpointUrlString, bodyObject: myObjectToPost)
Based on Illya Krit's answer
Details
Xcode Version 10.2.1 (10E1001)
Swift 5
Alamofire 4.8.2
Solution
import Alamofire
struct BodyStringEncoding: ParameterEncoding {
private let body: String
init(body: String) { self.body = body }
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
guard var urlRequest = urlRequest.urlRequest else { throw Errors.emptyURLRequest }
guard let data = body.data(using: .utf8) else { throw Errors.encodingProblem }
urlRequest.httpBody = data
return urlRequest
}
}
extension BodyStringEncoding {
enum Errors: Error {
case emptyURLRequest
case encodingProblem
}
}
extension BodyStringEncoding.Errors: LocalizedError {
var errorDescription: String? {
switch self {
case .emptyURLRequest: return "Empty url request"
case .encodingProblem: return "Encoding problem"
}
}
}
Usage
Alamofire.request(url, method: .post, parameters: nil, encoding: BodyStringEncoding(body: text), headers: headers).responseJSON { response in
print(response)
}
If you want to post string as raw body in request
return Alamofire.request(.POST, "http://mywebsite.com/post-request" , parameters: [:], encoding: .Custom({
(convertible, params) in
let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
let data = ("myBodyString" as NSString).dataUsingEncoding(NSUTF8StringEncoding)
mutableRequest.HTTPBody = data
return (mutableRequest, nil)
}))
I have done it for array from strings. This solution is adjusted for string in body.
The "native" way from Alamofire 4:
struct JSONStringArrayEncoding: ParameterEncoding {
private let myString: String
init(string: String) {
self.myString = string
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = urlRequest.urlRequest
let data = myString.data(using: .utf8)!
if urlRequest?.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest?.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest?.httpBody = data
return urlRequest!
}
}
And then make your request with:
Alamofire.request("your url string", method: .post, parameters: [:], encoding: JSONStringArrayEncoding.init(string: "My string for body"), headers: [:])
I've used answer of #afrodev as reference. In my case I take parameter to my function as string that have to be posted in request. So, here is the code:
func defineOriginalLanguage(ofText: String) {
let text = ofText
let stringURL = basicURL + "identify?version=2018-05-01"
let url = URL(string: stringURL)
var request = URLRequest(url: url!)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("text/plain", forHTTPHeaderField: "Content-Type")
request.httpBody = text.data(using: .utf8)
Alamofire.request(request)
.responseJSON { response in
print(response)
}
}
func paramsFromJSON(json: String) -> [String : AnyObject]?
{
let objectData: NSData = (json.dataUsingEncoding(NSUTF8StringEncoding))!
var jsonDict: [ String : AnyObject]!
do {
jsonDict = try NSJSONSerialization.JSONObjectWithData(objectData, options: .MutableContainers) as! [ String : AnyObject]
return jsonDict
} catch {
print("JSON serialization failed: \(error)")
return nil
}
}
let json = Mapper().toJSONString(loginJSON, prettyPrint: false)
Alamofire.request(.POST, url + "/login", parameters: paramsFromJSON(json!), encoding: .JSON)
My case, posting alamofire with content-type: "Content-Type":"application/x-www-form-urlencoded", I had to change encoding of alampfire post request
from : JSONENCODING.DEFAULT
to: URLEncoding.httpBody
here:
let url = ServicesURls.register_token()
let body = [
"UserName": "Minus28",
"grant_type": "password",
"Password": "1a29fcd1-2adb-4eaa-9abf-b86607f87085",
"DeviceNumber": "e9c156d2ab5421e5",
"AppNotificationKey": "test-test-test",
"RegistrationEmail": email,
"RegistrationPassword": password,
"RegistrationType": 2
] as [String : Any]
Alamofire.request(url, method: .post, parameters: body, encoding: URLEncoding.httpBody , headers: setUpHeaders()).log().responseJSON { (response) in
let parameters = ["foo": "bar"]
// 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))
Xcode 8.X , Swift 3.X
Easy Use;
let params:NSMutableDictionary? = ["foo": "bar"];
let ulr = NSURL(string:"http://mywebsite.com/post-request" as String)
let request = NSMutableURLRequest(url: ulr! as URL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let data = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted)
let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
if let json = json {
print(json)
}
request.httpBody = json!.data(using: String.Encoding.utf8.rawValue);
Alamofire.request(request as! URLRequestConvertible)
.responseJSON { response in
// do whatever you want here
print(response.request)
print(response.response)
print(response.data)
print(response.result)
}