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

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
}

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.

Cannot convert value of type 'inout NSNumber?' to expected argument type 'AutoreleasingUnsafeMutablePointer<AnyObject?>' error

I have this script use to check whether the *downloaded file from iCloud is available or not. But unfortunately I encountered error Cannot convert value of type 'inout NSNumber?' to expected argument type 'AutoreleasingUnsafeMutablePointer<AnyObject?>' in some lines of code. Please help me to solve this issue because it is my first time to create a code to check whether the downloaded file is available in the icloud or not.
Please refer to the image below as sample of the error and also codes are available below for your reference. Hope you could help me. Thank you.
Sample screenshot of error
//-------------------------------------------------------------------
// ダウンロードできるか判定 Judgment or can be downloaded
//-------------------------------------------------------------------
func downloadFileIfNotAvailable(_ file: URL?) -> Bool {
var isIniCloud: NSNumber? = nil
do {
try (file as NSURL?)?.getResourceValue(&isIniCloud, forKey: .isUbiquitousItemKey)
if try (file as NSURL?)?.getResourceValue(&isIniCloud, forKey: .isUbiquitousItemKey) != nil {
if isIniCloud?.boolValue ?? false {
var isDownloaded: NSNumber? = nil
if try (file as NSURL?)?.getResourceValue(&isDownloaded, forKey: .ubiquitousItemIsDownloadedKey) != nil {
if isDownloaded?.boolValue ?? false {
return true
}
performSelector(inBackground: #selector(startDownLoad(_:)), with: file)
return false
}
}
}
} catch {
}
return true
}
It looks like you copied and pasted some really old code. Besides, this is Swift, not Objective-C. Do not use NSURL or getResourceValue. Your code should look more like this:
if let rv = try file?.resourceValues(forKeys: [.isUbiquitousItemKey]) {
if let isInCloud = rv.isUbiquitousItem {
// and so on
}
}
And so on; the same pattern applied to other keys. Note that there is no .ubiquitousItemIsDownloadKey either. You can condense things like this:
if let rv = try file?.resourceValues(
forKeys: [.isUbiquitousItemKey, .ubiquitousItemDownloadingStatusKey]) {
if let isInCloud = rv.isUbiquitousItem {
if let status = rv.ubiquitousItemDownloadingStatus {
if status == .downloaded {
}
}
}
}

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

Data is Null error in GetDateTime()

Still.I get an error on this part.(another part of my codes where I really want to do is to put IsDBNull on it)
But the I know it'll not work in GetDateTime. Is there any possible solution?
data[key].ApproverList.Add(
new Approver() {
RequestID = key,
FullName = reader.IsDBNull(27) ? null : reader.GetString(27),
ApproveDate = reader.GetDateTime(28)
});
same as the
FullName with reader.IsDBNull(27) ? null : reader.GetString(27)
how about
ApproveDate = reader.GetDateTime(28)
What will be in here?
Try this
DateTime? startingDate;
if !reader.IsDBNull(reader.GetOrdinal("STARTINGDATE"))
{
startingDate = reader.GetDateTime(reader.GetOrdinal("STARTINGDATE"));
}
else
{
startingDate = null;
}
I know you are leaving ..

Resources