Alamofire request not sending post parameter - ios

I am trying to create an Alamofire request as follows:
//creating parameters for the post request
let parameters: Parameters=[
"modelo": modelo_id
]
let url_dispo = URL(string: "https://../calcular_precio.php")
Alamofire.request(url_dispo!, method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
print(response)
//to get status code
if let status = response.response?.statusCode {
switch(status){
case 201:
print("example success")
default:
print("error with response status: \(status)")
}
}
//to get JSON return value
if let result = response.result.value {
let JSON = result as! NSDictionary
print(JSON)
}
}
My issue is that the response from the url is telling me that the post parameter is not sended with the request.
I have checked the value for modelo_id and it is correct.
Is there anything wrong in my code?
Here you have the complete PHP script:
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['modelo']) ) {
// receiving the post params
$modelo= $_POST['modelo'];
// get the user by email and password
$user = $db->getPrecioByModelo($modelo);
if ($user != false) {
// use is found
$response["error"] = FALSE;
$response["id"] = $user["id"];
$response["precio"]["p1"] = $user["p1"];
$response["precio"]["p2"] = $user["p2"];
$response["precio"]["p3"] = $user["p3"];
$response["precio"]["p4"] = $user["p4"];
$response["precio"]["p5"] = $user["p5"];
$response["precio"]["p6"] = $user["p6"];
$response["precio"]["p7"] = $user["p7"];
$response["precio"]["p8"] = $user["p8"];
$response["precio"]["p9"] = $user["p9"];
$response["precio"]["p10"] = $user["p10"];
$response["precio"]["p11"] = $user["p11"];
$response["precio"]["p12"] = $user["p12"];
$response["precio"]["p13"] = $user["p13"];
$response["precio"]["p14"] = $user["p14"];
$response["precio"]["p15"] = $user["p15"];
$response["precio"]["p16"] = $user["p16"];
$response["precio"]["p17"] = $user["p17"];
$response["precio"]["p18"] = $user["p18"];
$response["precio"]["p19"] = $user["p19"];
$response["precio"]["p20"] = $user["p20"];
$response["precio"]["p21"] = $user["p21"];
$response["precio"]["p22"] = $user["p22"];
$response["precio"]["p23"] = $user["p23"];
echo json_encode($response);
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Wrong action! Please, try again!";
echo json_encode($response);
}
} else {
// required post params is missing
$response["error"] = TRUE;
$response["modelo"] = $modelo;
$response["error_msg"] = "Required parameters missing!";
echo json_encode($response);
}
?>
EDIT:
Here you have the debugger output:
modeloid 1069
SUCCESS: {
error = 1;
"error_msg" = "Required parameters email or password is missing!";
modelo = "<null>";
}
error with response status: 200
{
error = 1;
"error_msg" = "Required parameters email or password is missing!";
modelo = "<null>";
}

The problem is that you are sending the data with Alamofire using
JSONEncoding.default
and expecting your data on the backend as URL encoding. Change the encoding to:
URLEncoding.default
and you should be good to go.

Related

Post trade Order Binance Signature error

I am trying to make trade using binance api from ios.
Always gives error ["code": -1022, "msg": Signature for this request is not valid.]
Code:
public override func requestFor(api: APIType) -> NSMutableURLRequest {
let mutableURLRequest = api.mutableRequest
if let key = key, let secret = secret, api.authenticated {
var postData = api.postData
//postData["symbol"] = "BNBBTC"
//postData["timestamp"] = "\(Int(Date().timeIntervalSince1970 * 1000))"
postData["symbol"] = "BNBBTC"
postData["side"] = "SELL"
postData["type"] = "MARKET"
postData["recvWindow"] = "5000"
postData["quantity"] = "0.1"
postData["timestamp"] = "\(Int(Date().timeIntervalSince1970 * 1000))"
if let hmac_sha = try? HMAC(key: secret, variant: .sha256).authenticate(Array(postData.queryString.utf8)) {
let signature = Data(bytes: hmac_sha).toHexString()
postData["signature"] = signature
}
var postDataString = ""
if let data = postData.data, let string = data.string, postData.count > 0 {
postDataString = string
if case .GET = api.httpMethod {
mutableURLRequest.httpBody = data
} else if case .POST = api.httpMethod {
var urlString = mutableURLRequest.url?.absoluteString
urlString?.append("?")
urlString?.append(postData.queryString)
let url = URL(string: urlString!)
mutableURLRequest.url = url
}
api.print("Request Data: \(postDataString)", content: .response)
}
mutableURLRequest.setValue(key, forHTTPHeaderField: "X-MBX-APIKEY")
}
return mutableURLRequest
}
Edit: While using account api i am not facing any issues with the signature. It gives response as expected
I had same ... problem and I found answer. When you generate signature, inputs for Test Order and Account Info are different.
Inputs for account info:
string input = "timestamp=1535623795177";
string apiSecret = "YOUR API SECRET"
Inputs for test limit order:
string input = "symbol=ETHBTC&side=BUY&recvWindow=6500&type=LIMIT&timeInForce=GTC&quantity=100&price=0.1&timestamp=1535623795177";
string apiSecret = "YOUR API SECRET"
and generate signature working example (C#):
private string GenerateSignature(string input, string apiSecret)
{
var encoding = new UTF8Encoding();
byte[] keyByte = encoding.GetBytes(apiSecret);
byte[] messageBytes = encoding.GetBytes(input);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashMessage = hmacsha256.ComputeHash(messageBytes);
return String.Concat(hashMessage.Select(b => b.ToString("x2")));
}
}

Swifty JSON Not Working After Updating to Xcode 8

my JSON Respose is
{
code = 1;
document = (
{
Address1 = "<null>";
Address2 = "<null>";
City = "<null>";
CompanyID = 1;
CompanyName = Innohabit;
ContactNumber = "<null>";
Designation = "<null>";
DesignationID = 36;
DesignationName = dev;
Email = "uday.mishra#Gmail.com";
FCMRegistrationToken = "";
GCMRegistrationToken = "";
Gender = Male;
ID = 9;
IsActive = 1;
IsFirstLogin = 1;
LastLogin = "2016-09-21 05:45:33";
Name = "Uday Mishra";
Password = "";
ProfilePic = "";
RegisterationDate = "2016-03-04 07:42:42";
UserTwitter = "<null>";
Username = "uday.mishra#Gmail.com";
}
);
message = "Record found";
status = success;
}
And Trying to Convert the respose using Swifty Json Like this
case .success:
print(response)
let jsonResponse = JSON(response.data)
print("JSON")
let jsonData = jsonResponse["document"]
print(jsonResponse)
print(jsonData[0])
But I am Not getting the desired result, the Output is
{
code = 1;
document = (
{
Address1 = "<null>";
Address2 = "<null>";
City = "<null>";
CompanyID = 1;
CompanyName = Innohabit;
ContactNumber = "<null>";
Designation = "<null>";
DesignationID = 36;
DesignationName = dev;
Email = "uday.mishra#Gmail.com";
FCMRegistrationToken = "";
GCMRegistrationToken = "";
Gender = Male;
ID = 9;
IsActive = 1;
IsFirstLogin = 1;
LastLogin = "2016-09-21 05:45:33";
Name = "Uday Mishra";
Password = "";
ProfilePic = "";
RegisterationDate = "2016-03-04 07:42:42";
UserTwitter = "<null>";
Username = "uday.mishra#Gmail.com";
}
);
message = "Record found";
status = success;
}
JSON
unknown
null
As u can see the response is getting printed ,but the print(jsonResponse) and print(jsonData[0])
is printing Unknown and null can anyone help me how i can serialise the data properly into JSON format from DataRespose
please suggest any alternative method or if I m doing any mistake please help me.
Try to use bellow code :
if let jsonResponse: AnyObject = JSON(response.data){
let jsonData = jsonResponse["document"]
print(jsonResponse)
print(jsonData[0])
}
Edit:
I read below statement on this
The platform of the target Pods (iOS 7.1) is not compatible with SwiftyJSON (2.1.3) which has a minimum requirement of OS X 10.9 - iOS 8.0.
EDIT:
I replaced SwiftyJson.swift with the one in Xcode 6.3 branch and it worked fine now no errors. :-)
So try to follow that step.
I tried this and it is working fine for me.
Alamofire.request(url, method: .post,parameters: parameters).validate().responseJSON { response in
switch response.result {
case .success(let data):
//print(response)
let jsonResponse = JSON(data)
print("JSON")
let jsonData = jsonResponse["document"][0]
print("Email")
print(jsonData["Email"])
case .failure(let error):
print(error)
}
}

HttpClient.PostAsync returning Null on A Web API POST

I am trying to get response from an API on few GET and POST calls, whenever i try to get Response from a web API POST it gives an System.NullReferenceException: Object reference not set to an instance of an object.. I am using PostAsync to get response. It works absolutely fine on my local machine but is returning NULL response on deployment machine.
#region API_CALL
System.Net.Http.HttpClient Client = new System.Net.Http.HttpClient();
string CompleteURL = URL.Trim() + URL_FromJSON.Trim();
#region URL Construct For GET Requests
CompleteURL = GetURL(ParameterValue, CallType_FromJSON, CompleteURL);
#endregion URL Construct For GET Requests
string URLContent = string.Empty;
Client.BaseAddress = new System.Uri(CompleteURL);
byte[] cred = UTF8Encoding.UTF8.GetBytes(ClientID.Trim() + Constants.APIConstants.ColonConnector + ClientPass.Trim());
string Encoded = Convert.ToBase64String(cred);
Client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(Constants.APIConstants.AuthTypeBearer, accessToken);
Client.DefaultRequestHeaders.Host = IPAddress.Trim();
CacheControlHeaderValue val = new CacheControlHeaderValue();
val.NoCache = true;
Client.DefaultRequestHeaders.CacheControl = val;
Client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(Constants.APIConstants.ContentType));
Client.DefaultRequestHeaders.Add(Constants.APIConstants.LicenseKey, LiscenseKEY);
Client.DefaultRequestHeaders.Add(Constants.APIConstants.PostmanToken, PostmanToken);
//client.DefaultRequestHeaders.Add(Constants.APIConstants.AccessToken, accessToken);
System.Net.Http.HttpContent Content = new StringContent(JSONData, UTF8Encoding.UTF8, Constants.APIConstants.ContentType);
// Only for debug purpos:
LogManager.Logger.Invoke(LogLevels.TraceDetail, Source, "Request to API: " + JSONData, Request.ActorID);
HttpResponseMessage Message = new HttpResponseMessage();
if (CallType_FromJSON == Constants.HttpMethod.Post)
{ Message = Client.PostAsync(CompleteURL, Content).Result; }
else if (CallType_FromJSON == Constants.HttpMethod.Get)
{ Message = Client.GetAsync(CompleteURL, HttpCompletionOption.ResponseContentRead).Result; }
string Description = string.Empty;
#region Response Logging
try
{
LogManager.Logger.Invoke(LogLevels.TraceDetail, Source, "Response from API: " + Message.Content.ReadAsStringAsync().Result, Request.ActorID);
}
catch(Exception EX)
{
LogManager.Logger.Invoke(LogLevels.TraceError, Source, "Exception while logging response from API" + EX.ToString()+"Stack: "+EX.StackTrace, Request.ActorID);
}
#endregion Response Logging
if (Message.IsSuccessStatusCode)
{
string Result = Message.Content.ReadAsStringAsync().Result;
ResponseJson = Result;
Description = Result;
}
else
{
try
{
string Result1 = Message.Content.ReadAsStringAsync().Result;
LogManager.Logger.Invoke(LogLevels.TraceInfo, Source, "Failed: ... Recieved JSON: " + Result1, Request.ActorID);
}
catch { }
return new TransactionResponse() { Response = Constants.ResponseCodes.Error };
}
#endregion API_CALL
break;
}
TransactionResponse Response = new TransactionResponse();
Response.Response = ResponseJson;
return Response;
}
catch (Exception Ex)
{
LogManager.ExpLogger.Invoke(Source, Ex, Request.ActorID);
return new TransactionResponse() { Response = Constants.ResponseCodes.Error };
}
the object : Message is null after execution of Message = Client.PostAsync(CompleteURL, Content).Result
Try reading as string asynch with the in the reach of postasynch, use it with the same block of code it works,
if (CallType_FromJSON == Constants.HttpMethod.Post)
{ Message = Client.PostAsync(CompleteURL, Content).Result; }
else if (CallType_FromJSON == Constants.HttpMethod.Get)
{ Message = Client.GetAsync(CompleteURL, HttpCompletionOption.ResponseContentRead).Result; }
string Description = string.Empty;
example:
var = httpresult.content.readasstringasyhnc();
You can also typecast to any model you want her.

Getting crash when "<null>" as response from api is received in SWIFT

Getting the image url null as response from api, is there any way for fix it. Response from api is:
"image_path" = "<null>";
Tried to handle it like this:
if !(arrList.objectAtIndex(indexPath.row).valueForKey("media")?.objectAtIndex(0).valueForKey("image_path") is NSNull) {
// optional is NOT NULL, neither NIL nor NSNull
}
It is still crashing please guide.
Update:
Found the problem, null was not the issue actually. Posting the response below to make things clear.
media = (
{
id = "97eb48a0-429a-11e6-873c-ad7b848648f1";
"image_path" = "https://s3-eu-west-1.mazws.com/facebook_profile_images/15105131.png";
"room_post_id" = "97c572e0-429a-11e6-b72b-fd489f63a1fc";
"user_id" = "66fe22a0-4296-11e6-a1d9-69dc307add4b";
"video_path" = "<null>";
},
{
id = "981a6880-429a-11e6-b039-736a0bf954dc";
"image_path" = "<null>";
"room_post_id" = "97c572e0-429a-11e6-b72b-fd489f63a1fc";
"user_id" = "66fe22a0-4296-11e6-a1d9-69dc307add4b";
"video_path" = "https://s3-eu-west-1.naws.com/facebook_profile_images/1255803.mp4";
}
);
This is the normal response, now the response where trouble is:
media = (
);
Can it be handle any how? Please guide.
Try like this .. it'll not crash
if let imgPath = arrList.objectAtIndex(indexPath.row).valueForKey("media")?.objectAtIndex(0).valu‌​eForKey("image_path") as? String {
//... your value is string
}
Let me guess types by information you provided:
if let arrList = arrList as? NSArray,
firstObject = arrList.objectAtIndex(indexPath.row) as? NSDictionary,
media = firstObject.valueForKey("media") as? NSArray,
secondObject = media.objectAtIndex(0) as? NSDictionary,
image_path = secondObject.valueForKey("image_path") as? String {
print(image_path)
// now validate your string
}
Validating your string can be like this:
if !image_path.isEmpty && image_path != "<null>" {
//do something
}
or like this:
if !image_path.isEmpty {
if let image_pathURL = NSURL(string: image_path), _ = image_pathURL.host {
//do something
}
}
Why don't to simple check with == like:
if !(arrList.objectAtIndex(indexPath.row).valueForKey("media")?.objectAtIndex(0).valueForKey("image_path") == "<null>")
if let image = myJson["image_path"] as? String {
imageView.image = image
}
else {
imageview.image = "default.png"
}
also try this
if !(arrList.objectAtIndex(indexPath.row).valueForKey("media")?.objectAtIndex(0).valueForKey("image_path") == "<null>") {
// optional is NOT NULL, neither NIL nor NSNull
}

How can I get the correct JSON text in AFNetworking in swift

I used AFNetworking to make a GET request. The result I got is not a JSON string but it should be a JSON string.
I want to get the following JSON text:
{
"code": 200,
"message": "success",
"data": [
{
"goods_id": "31",
"goods_item": "DA55098",
"goods_price": "0",
"goods_shop_price": "198",
"class_id": "45",
"goods_thumbnail_image": "/public/upload/goods/20151122/thumb_fcd13f057fa51d2d72826f7e26625b7c.jpg",
"goods_name": "Product name",
"buy_num": 0,
"faverite_num": "0"
}
]
}
But I got this:
{
code = 200;
data = (
{
"buy_num" = 0;
"class_id" = 45;
"faverite_num" = 0;
"goods_id" = 31;
"goods_item" = DA55098;
"goods_name" = "Product name";
"goods_price" = 0;
"goods_shop_price" = 198;
"goods_thumbnail_image" = "/public/upload/goods/20151122/thumb_fcd13f057fa51d2d72826f7e26625b7c.jpg";
}
);
message = "success";
}
Here is my code:
override func viewDidLoad() {
super.viewDidLoad()
let api = "http://jjd.imlc.me/api/index/"
manager.GET(
api,
parameters: nil,
success: onSuccess,
failure: onFailure
)
}
func onSuccess(operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void{
let description = responseObject.description
print(description)
}
You need to set the response serializer of your manager to an instance of AFJSONResponseSerializer like so (before you make your request)
manager.responseSerializer = AFJSONResponseSerializer()
You are confusing a JSON document converted to text with a JSON document, parsed and converted to a dictionary, and it's description displayed.
The description of a dictionary is not a JSON document. What you see is normal. Nothing to worry about.

Resources