Can't get correct api call in swift 3 - ios

I tried this particular API in postman, and it returns a fine result.
Thus, i created a parameter
["JsonRequest": "{\"header\":\"GetLocationListReq\",\"accessKey\":\"fakeKey\"}"]
but when i pass this parameter when calling this API using swift and alamofire in my Xcode project, i always get back an error.
For those who are interested, my apiRouter is
//
// WINAPIRouter.swift
// Winner21
//
// Created by Lin Hairui on 27/4/17.
// Copyright © 2017 Pioneers & Leaders (Publishers). All rights reserved.
//
import Foundation
import Alamofire
enum WINAPIRouter : URLRequestConvertible {
static let baseURL = Constant.baseURL
case get(String)
case create([String:Any],String?)
case delete(String)
func asURLRequest() throws -> URLRequest {
var method : HTTPMethod {
switch self {
case .get:
return HTTPMethod.get
case .create:
return HTTPMethod.post
case .delete:
return HTTPMethod.delete
}
}
let params:(Dictionary<String, Any>?) = {
switch self {
case .get, .delete:
return nil
case .create(let params, _):
var fieldParams = params
fieldParams["accessKey"] = Constant.kAPIAccessKey
let jsonData: NSData
do {
jsonData = try JSONSerialization.data(withJSONObject: fieldParams, options: JSONSerialization.WritingOptions()) as NSData
let jsonString = NSString(data: jsonData as Data, encoding: String.Encoding.utf8.rawValue) as! String
let authParam : [String : Any] = [
"JsonRequest" : jsonString
]
print("google was here \(authParam)")
return authParam
} catch _ {
print ("JSON Failure")
}
return nil
}
}()
let url : URL = {
return URL(string: Constant.baseURL)!
}()
var urlRequest = URLRequest(url: url)
// urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
// urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
urlRequest.httpMethod = method.rawValue
print("facebook was here = \(urlRequest.httpMethod!)")
let encoding = JSONEncoding.default
print("yahoo was here \(params)")
//let facejsonData = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions())
return try encoding.encode(urlRequest, with: params!)
}
}
And, i call the API using the following function.
Alamofire.request(WINAPIRouter.create(params, nil)).responseJSON

I think response from API is not in JSON, try to use URL encoding like below,
Alamofire.request(path, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil) . responseString(completionHandler: { ( dataResponse ) in
/// print response
})

Related

Authorization Header not setting in Alamofire 5?

I am setting the basic auth token to my URLRequest and using Alamofire to execute.
I set 3 headers, content, accept and auth...content and accept are visible in the network traffic but auth is not. It is available if i print the headers of the URLRequest before its sent...
Any ideas here? as i dont see how its removing the auth header before posting
Code as follows:
// Construct url
let url = try APIConstants.baseUrl.asURL()
// Append path
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
// Determine HTTP method
urlRequest.httpMethod = method.rawValue
let headers: HTTPHeaders = [
.contentType(APIConstants.ContentType.json.rawValue),
.accept(APIConstants.ContentType.json.rawValue),
]
if let token = token {
urlRequest.addValue("\(APIConstants.API.token.rawValue) \(token.key)",
forHTTPHeaderField: "Authorization")
}
urlRequest.headers = headers
// Add http body to request
if let parameters = parameters {
do {
let data = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
urlRequest.httpBody = data
} catch (_) {
print("APIRouter: Failed to parse body into request.")
}
}
//Encoding
let encoding: ParameterEncoding = {
switch method {
case .get:
return URLEncoding.default
default:
return JSONEncoding.default
}
}()
return try encoding.encode(urlRequest, with: parameters)
}
In my rest client i execute like this:
return Observable<T>.create { observer in
let request = AF.request(urlConvertible).responseDecodable { (response: DataResponse<T, AFError>) in
switch response.result {
case .success(let value):
observer.onNext(value)
observer.onCompleted()
case .failure(let error):
switch response.response?.statusCode {
case 403:
observer.onError(APIError.forbidden)
case 404:
observer.onError(APIError.notFound)
case 409:
observer.onError(APIError.conflict)
case 500:
observer.onError(APIError.internalServerError)
default:
observer.onError(error)
}
}
}
return Disposables.create {
request.cancel()
}
}
}
Edit:
Updated func to show further issue:
func asURLRequest() throws -> URLRequest {
// Construct url
let url = try APIConstants.baseUrl.asURL()
// Append path
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
// Determine HTTP method
urlRequest.httpMethod = method.rawValue
let headers: HTTPHeaders = [
.contentType(APIConstants.ContentType.json.rawValue),
.accept(APIConstants.ContentType.json.rawValue),
.authorization("Token a5555485aa251b28fdsfasdfdsb379c131fddad")
]
urlRequest.headers = headers
// Add http body to request
if let parameters = parameters {
do {
let data = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
urlRequest.httpBody = data
} catch (_) {
print("APIRouter: Failed to parse body into request.")
}
}
//Encoding
let encoding: ParameterEncoding = {
switch method {
case .get:
return URLEncoding.default
default:
return JSONEncoding.default
}
}()
return try encoding.encode(urlRequest, with: parameters)
}
After setting the Authorization header in your URLRequest:
urlRequest.addValue("\(APIConstants.API.token.rawValue) \(token.key)", forHTTPHeaderField: "Authorization")
then you override all the request's headers by setting headers property:
urlRequest.headers = headers
A nice solution would be to update the headers that you already created above, like this:
var headers: HTTPHeaders = [
.contentType(APIConstants.ContentType.json.rawValue),
.accept(APIConstants.ContentType.json.rawValue),
]
if let token = token {
headers.add(.authorization("\(APIConstants.API.token.rawValue) \(token.key)"))
}
urlRequest.headers = headers
Another solution is to use KeyValue pair as follows:
var header: HTTPHeaders = [:]
if let token = getValueFromUserDefaults(keyName: "authToken") as? String {
header["Authorization"] = token
}
I always use this method. It's more handy for me.

iOS Swift Http request post method using header x-www-form-urlencoded?

I have to make an API call with headers as application/x-www-form-urlencoded value as a JSON string. When give parameter value and header in postman, it works fine and returns status code 200 ok. Here i am using backend node js . Post method does not work in front end. Dont know what is the issue.
Errors:
Sometimes i am getting request time out,
NSUrlfailingstring, finished with status code 1001
Here is the code of my backend :
var status = {
SUCCESS : 'success',
FAILURE : 'failure'
}
var httpStatus = {
OK : HttpStatus.OK,
ISE : HttpStatus.INTERNAL_SERVER_ERROR,
BR : HttpStatus.BAD_REQUEST
}
exports.likes= function(req, res){
var Username =req.body.username;
var likecount=req.body.count;
var likedby = req.body.likedby;
var postId = req.body.postId;
var tokenId = req.body.tokenId;
var message = {
to: tokenId,
collapse_key: '',
data: {
name:Username,
Message:"Content about message",
Redirect:"TopostId : "+postId,
time: ""
},
notification: {
title: "Hey Buddy , Someone have liked your post",
body: likedby +"Likedyourpost",
icon: "notification"
}
};
fcm.send(message)
.then(function (response) {
console.log("Successfully sent with response: ", response);
res.status(httpStatus.OK).json({
status: status.SUCCESS,
code: httpStatus.OK,
error:''
});
return;
})
.catch(function (err) {
console.log(err);
});
};
module.exports = function(app) {
app.post('/likesnotification', notification.likes);
app.post('/commentsnotification', notification.comments);
app.post('/othernotification', notification.othernot);
app.post('/followrequset', notification.followreq);
app.post('/followresponse', notification.followres);
app.post('/publicaccountfollow', notification.publicacfollow);
};
Here is my front code in ios Swift:
Try 1:
func postNotification(postItem: String, post: Post) {
print("Get token from post:::",post.token)
print(postItem)
let token = UserDefaults.standard.string(forKey: "token")
let headers: HTTPHeaders = ["Content-Type" :"application/x-www-form-urlencoded"]
let parameters : [String:Any] = ["count":post.likeCount!, "likedby":currentName, "postId=":postItem, "token": post.token!]
Alamofire.request("http://highavenue.co:9000/likesnotification/", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if let data = response.result.value{
print(data)
}
break
case .failure(_):
print(response.result.error as Any)
break
}
}
}
Try 2:
var parameters = [String:Any]()
parameters["count"] = post.likeCount!
parameters["likedby"] = currentName
parameters["postId"] = postItem
parameters["token"] = post.token!
let Url = String(format: "http://highavenue.co:9000/likesnotification")
guard let serviceUrl = URL(string: Url) else { return }
// let loginParams = String(format: LOGIN_PARAMETERS1, "test", "Hi World")
let parameterDictionary = parameters
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {
return
}
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options:
[])
print(json)
}catch {
print(error)
}
}
}.resume()
Any help much appreciated pls.
I seen your code you are suppose to call the header parameter which was you create for it. You are not pass header in alamofire request method.
Like below :
let headers: HTTPHeaders = ["Content-Type" :"application/x-www-form-urlencoded"]
let parameters : [String:Any] = ["count":post.likeCount!, "likedby":currentName, "postId=":postItem, "token": post.token!]
Alamofire.request("http://highavenue.co:9000/likesnotification/", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if let data = response.result.value{
print(data)
}
break
case .failure(_):
print(response.result.error as Any)
break
}
}
}

Swift - How to send POST request with "x-www-form-urlencoded" content-type

I searched a lot and there's no clear instruction for sending POST request with "x-www-form-urlencoded" content-type.
i want to know how to do that and if you know how to do it with Alamofire it would be even better.
any help will be appreciated.
Hope you are searching for this one or give us more explanation in code so we get it easily:
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
let parameters = [
]
Alamofire.request("urlString", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case.success(let data):
print("success",data)
case.failure(let error):
print("Not Success",error)
self.view.makeToast(message: "Server Error!!")
}
}
I used below code in swift 4.2
guard let url = URL(string: "http://192.168.88.129:81/authenticate") else {
return
}
let user1 = username.text!
let pass = passwordfield.text!
print(user1)
print(pass)
let data : Data = "username=\(user1)&password=\(pass)&grant_type=password".data(using: .utf8)!
var request : URLRequest = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");
request.setValue(NSLocalizedString("lang", comment: ""), forHTTPHeaderField:"Accept-Language");
request.httpBody = data
print("one called")
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// vs let session = URLSession.shared
// make the request
let task = session.dataTask(with: request, completionHandler: {
(data, response, error) in
if let error = error
{
print(error)
}
else if let response = response {
print("her in resposne")
}else if let data = data
{
print("here in data")
print(data)
}
DispatchQueue.main.async { // Correct
guard let responseData = data else {
print("Error: did not receive data")
return
}
let decoder = JSONDecoder()
print(String(data: responseData, encoding: .utf8))
do {
// let todo = try decoder.decode(T.self, from: responseData)
// NSAssertionHandler(.success(todo))
} catch {
print("error trying to convert data to JSON")
//print(error)
// NSAssertionHandler(.failure(error))
}
}
})
task.resume()
}
Try this following method using Alamofire
Alamofire.request("yourSide", method: .post, parameters: parameters, encoding: URLEncoding.default)
If it doesn't work, which is unlikely, use this following code
Alamofire.request("yourSide", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)

Post method request Alamofire

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

POST request with a simple string in body with Alamofire

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)
}

Resources