Swifty JSON Not Working After Updating to Xcode 8 - ios

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

Related

Alamofire request not sending post parameter

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.

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

Obj-C: NSString crashes with error "Terminating app due to uncaught exception NSInvalidArgumentException"?

For some reason, the following line in my app is returned NULL, and thus, crashes my app:
NSString *address = [session user][#"field_street_address"][#"und"][0][#"safe_value"];
Which, I don't understand, as my console below states that data is returned for field_street_address. Is there something wrong with that line that I'm just not seeing? I've been staring at this for a while and I feel like I'm missing something obvious.
ViewController.m
NSDictionary *userDictInfo = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:#"diosSession"]];
DIOSSession *session = [DIOSSession sharedSession];
[session setUser:userDictInfo];
[session user];
NSString *address = [session user][#"field_street_address"][#"und"][0][#"safe_value"];
Console ([session user] log):
2017-10-06 14:06:22.226970-0700 app[828:193706] {
sessid = "DRY0fOXtO_FZOIeowFVVq8oalaFnKSe";
"session_name" = SESS2bb8896be0f16543ff3c6a;
token = giCdHBuw967IaSxDB34m0Evzf1HI3DIK6;
user = {
access = 1507310936;
created = 1459875505;
data = {
"ckeditor_auto_lang" = t;
"ckeditor_default" = t;
"ckeditor_lang" = en;
"ckeditor_show_toggle" = t;
"ckeditor_width" = "100%";
};
"field_address" = {
und = (
{
format = "<null>";
"safe_value" = "1325 Fake Street";
value = "1325 Fake Street";
}
);
};
"field_childrenunder" = {
und = (
{
format = "<null>";
"safe_value" = No;
value = No;
}
);
};
"field_city" = {
und = (
{
format = "<null>";
"safe_value" = Van;
value = Van;
}
);
};
"field_emergency_facility" = {
und = (
{
format = "<null>";
"safe_value" = Yes;
value = Yes;
}
);
};
"field_first_name" = {
und = (
{
format = "<null>";
"safe_value" = Brittany;
value = Brittany;
}
);
};
"field_last_name" = {
und = (
{
format = "<null>";
"safe_value" = B;
value = B;
}
);
};
"field_phonenumber" = {
und = (
{
format = "<null>";
"safe_value" = 2369893091;
value = 2369893091;
}
);
};
"field_photo_path" = {
und = (
{
format = "<null>";
"safe_value" = "sites/default/files/stored/1507092784.jpg";
value = "sites/default/files/stored/1507092784.jpg";
}
);
};
"field_points_balance" = {
und = (
{
format = "<null>";
"safe_value" = 12;
value = 12;
}
);
};
"field_postal_code" = {
und = (
{
format = "<null>";
"safe_value" = 000000;
value = 000000;
}
);
};
"field_private_message_notify" = {
und = (
{
value = 1;
}
);
};
"field_profile_photo" = {
und = (
{
alt = "";
fid = 237;
"field_file_image_alt_text" = (
);
"field_file_image_title_text" = (
);
filemime = "image/jpeg";
filename = "1507092784.jpg";
filesize = 16084;
height = 296;
metadata = {
height = 296;
width = 300;
};
"rdf_mapping" = (
);
status = 1;
timestamp = 1507108254;
title = "";
type = image;
uid = 47;
uri = "public://stored/1507092784.jpg";
width = 300;
}
);
};
"field_property_type" = {
und = (
{
format = "<null>";
"safe_value" = House;
value = House;
}
);
};
"field_province" = {
und = (
{
format = "<null>";
"safe_value" = BC;
value = BC;
}
);
};
"field_special_skills" = {
und = (
{
format = "<null>";
"safe_value" = "Oral medication";
value = "Oral medication";
}
);
};
"field_star_rating" = {
und = (
{
format = "<null>";
"safe_value" = 1;
value = 1;
}
);
};
"field_street_address" = {
und = (
{
format = "<null>";
"safe_value" = "1325 Fake Street";
value = "1325 Fake Street";
}
);
};
"field_supervision" = {
und = (
{
format = "<null>";
"safe_value" = No;
value = No;
}
);
};
"field_userbio" = {
und = (
{
format = "<null>";
"safe_value" = "Hi my name is Brittany.";
value = "Hi my name is Brittany.";
}
);
};
language = "";
login = 1507320712;
mail = "brittany-b#shaw.ca";
name = Brittany;
picture = "<null>";
"rdf_mapping" = {
homepage = {
predicates = (
"foaf:page"
);
type = rel;
};
name = {
predicates = (
"foaf:name"
);
};
rdftype = (
"sioc:UserAccount"
);
};
roles = {
2 = "authenticated user";
};
signature = "";
"signature_format" = "filtered_html";
status = 1;
theme = "";
timezone = UTC;
uid = 47;
};
}
If the log output in your question is from logging [session user] then you need to first access the #"user" key.
NSString *address = [session user][#"user"][#"field_street_address"][#"und"][0][#"safe_value"];
BTW - for issues like this it really helps to break down the code:
NSDictionary *sessionUser = [session user];
NSDictionary *user = sessionUser[#"user"];
NSDicitonary *streetAddr = user[#"field_street_address"];
// etc.
Then you can see where you start getting nil and look at the previous results to determine where things are going wrong.

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
}

Facebook Graph API - Status updates

I am currently using the Graph API to retrieve the News Feed for a user. However, some Posts of type "update" do not return any info on the original post e.g. in the result extract posted below, the story is "Joubert Nel commented on a link", but there is no info included as to what the link is, or the picture that goes with it. How can I obtain this info please?
actions = (
{
link = "https://www.facebook.com/637106301/posts/520940825396";
name = Comment;
}
);
comments = {
data = (
{
"can_remove" = 0;
"created_time" = "2014-03-15T13:06:43+0000";
from = {
id = 100000194244146;
name = "Laurie Edwards";
};
id = "520940825396_133907";
"like_count" = 2;
message = "Or you could just come home for a while!";
"user_likes" = 0;
},
);
paging = {
cursors = {
after = "MTI=";
before = "MQ==";
};
};
};
"created_time" = "2014-03-15T14:41:56+0000";
from = {
id = 637106301;
name = "Joubert Nel";
};
id = "637106301_520940825396";
likes = {
data = (
{
id = 214500098;
name = "Samuel Freilich";
},
{
);
paging = {
cursors = {
after = "OTUwMTE2OA==";
before = MjE0NTAwMDk4;
};
};
};
privacy = {
value = "";
};
story = "Joubert Nel commented on a link.";
"story_tags" = {
0 = (
{
id = 637106301;
length = 11;
name = "Joubert Nel";
offset = 0;
type = user;
}
);
};
type = status;
"updated_time" = "2014-03-15T14:41:56+0000";
is the link posted by Joubert? or using app you have permission. sounds like you don't have permission to post(link) but u have permission to Joubert activities

Resources