check the returned value is not NULL - iphone

I trie to check if the returned value from objectForKey is not NULL
if([[fbResult objectForKey:#"current_location"]objectForKey:#"country"])
formViewController.country=[[fbResult objectForKey:#"current_location"]objectForKey:#"country"];
But i have an error on the first line
UPDATE
fbResult is a JSON string,if the user has puted ​​his city and his country in facebook it look like :
"birthday_date" = "07/*****9";
"contact_email" = "***mehdi#hotmail.fr";
"current_location" = {
city = Tunis;
country = Tunisia;
id = 11166369***;
name = "Tunis, Tunisia";
state = Qabis;
zip = "";
};
locale = "fr_FR";
name = "Mehdi ****el";
pic = "https://fbcdn-profile-a.akamaihd.net/hprofile-********_s.jpg";
sex = male;
uid = 530****;
}
and if the user did not put his country and city it look like :
{ "birthday_date" = "02/*3/19**";
"contact_email" = "kev**kevin#gmail.com";
"current_location" = "<null>";
locale = "fr_FR";
name = "Aude ***";
pic = "http://profile.ak.fbcdn.net/hprofile-ak-snc4/4***2_**8_1112_s.jpg";
sex = female;
uid = 11***04*;
}
error is
-[NSObject(NSObject) doesNotRecognizeSelector:] + 96

Checking for existence of an object within a dictionary that is nested in another dictionary is not going to catch all occurrences of bad data.
To make your code more solid
id current_location = [fbResult objectForKey:#"current_location"];
if (current_location != nil && [current_location class] != [NSNull class]) {
id country = [current_location objectForKey:#"country"];
if (country != nil) {
formViewController.country= country;
} else {
// current_location has no country
}
} else {
// fbResult has no current_location
}
If the current_location is supposed to be a dictionary you can swap out id currentLocation with NSDictionary * currentLocation
from your update, your current_location can potentially be an instance of NSNull
you can check against that with
[yourObject class] != [NSNull class]

Related

How can I extract a string and number from a larger based on a unique pattern in flutter?

Given the following string structure:
Mark;12345 wrote: // Username = Mark ID# = 12345
Alex-Johnson;747645 wrote: // Username = Alex-Johnson ID# = 747645
Felix#felix.com;83213 wrote: // Username = Felix#felix.com ID# = 83213
Jack65;123123 wrote: // Username = Jack65 ID# = 123123
John wrote: // Username = John ID# = null
Id like to ideally extract the username and the userid, which are going to be separated by a ;. There may also be times when the ID# will be blank as in the last example string
Any ideas?
// You can try this code. Here I used null-safety, regexp ,list and maps
void main()
{
String str = '''Mark;12345
Alex-Johnson;747645
Felix#felix.com;83213
Jack65;123123
John
Bill
;1111''';
Map<String?,String?> lineMaped= {};
//This map will receive the username and the userid
List<String> listOfEachLine= str.split('\n');
//Each line of the text is put in the list
RegExp searchForName= new RegExp(r'([\w._#-]+)(?:[;])([\d]*)');
//this RegExp only have a match when the line has an ';' and a letter or digit
//before
for (int i=0;i < listOfEachLine.length;i++){
RegExpMatch? match = searchForName.firstMatch(listOfEachLine[i]);
//the firstMatch method can return null, for this situation I use the '?'
//in type declaration
if(';'.allMatches(listOfEachLine[i]).length == 0){
//condition: there isn't any ';' in the line, in other words: when ID#
//is blank
lineMaped.addAll({listOfEachLine[i] : ''});
} else {
if (match != null && match.groupCount>1) {
//this if ensures the non-nullable of variables
lineMaped.addAll({match.group(1): match.group(2)});
} //if
} //else
} //for
lineMaped.forEach((k,v) => print('\n ${k} <-> ${v}'));
} //main
//Output:
//Mark <-> 12345
//Alex-Johnson <-> 747645
//Felix#felix.com <-> 83213
//Jack65 <-> 123123
//John <->
//Bill <->
Try to do it with a substring. You can also do it with a split I think.
String text = 'Mark;12457 wrote:';
if(text.contains(';')){
int size = text.indexOf(';');
int size2= text.indexOf('wrote:');
String userName = text.substring(0,size);
String id = text.substring(size+1,size2); //1 is the number of character in ('...')
print('username: $userName, id#: $id');
}else{
int size= text.indexOf('wrote:');
String userName = text.substring(0,size);
print('username: $userName, id#: null');
}
much simplier
var str = 'Mark;12345 wrote:';
final arr = str.replaceAll(' wrote:', '').split(';');
final userName = arr[0];
final userId = arr.length > 1 ? arr[1] : null;
print('$userName $userId');

Load Specific data from JSON with Random Values Swift

I am using firebase and I am trying to retrieve data from Firebase Database which is working well however when I call "postDict" I get.
["-KPZAOg58kUdqwYMzlDJ":
{
description = jpeg;
listingImageURL = "https://firebasestorage.googleapis.com/v0/b/hype-central.appspot.com/o/lidsafstings%2FC73FdfB8A0-968df7-44DB-B96B-A10DC1E3A2B7.png?alt=media&token=b6e296f2-8854-4b76-9bfc-470dfd69d11f2f";
location = jpeg;
price = 54;
title = jpeg;
userDisplayName = "Brandon YOIO";
userid = pRuwvL7WyzQpY0G22ZLYCmTTemB3;
},
"-KPZ0yLhcfLvP9YWNjbC": {
description = "Description ofvaroe";
listingImageURL = "https://firebadfasestorage.googleapis.com/v0/b/hype-central.appspot.com/o/listings%2F0ACdasfCD645-2E2C-4936-B3DF-37EC55AA0157.png?alt=media&token=b321dasff42f-75b5-4eb3-b129-b0a902cc5926";
location = Vancouver;
price = 34;
title = eclipse;
userDisplayName = "Brandon YOIO";
userid = pRuwvL7WyzQpY0G22ZLYCmTTemB3;
},
"-KPoCsNS63JZdbTJIdaP": {
description = Brandon;
listingImageURL = "https://firebadasfsestorage.googleapis.com/v0/b/hype-central.appspot.com/o/listings%2FOptional(%22pRuwvL7WyzQpY0G22ZLYCmTTemB3%22)%2F3EACE28E-D28A-464A-B6D0-FB502E9dafsB4775.jpeg?alt=media&token=1d45bc7b-7273-4d33-8ccd-755f3102a23c";
location = BRANDON;
price = BRANDON;
title = BRANDON;
userDisplayName = "Brandon YOIO";
userid = pRuwvL7WyzQpY0G22ZLYCmTTemB3;
},
"-KP_Y7ug7hwrHtW6VNqV": {
description = "Description ofvaroe";
listingImageURL = "https://firebaseddasfstorage.googleapis.com/v0/b/hype-central.appspot.com/o/listings%2FC5daf7991BA-D7E0-4C8A-96E7-0DB17EEBABD7.jpeg?alt=media&token=efd03b4d-6964-4685-9b48-5ed36a4ceb59";
location = "";
price = "";
title = "";
userDisplayName = "Brandon Mayhew";
userid = pRuwvL7WyzQpY0G22ZLYCmTTemB3;
}]
If I call "postDict["-KPZAOg58kUdqwYMzlDJ"]["title"]" It will print the title which is exactly what I want however how do I get an array of all the titles in this JSON format (not just the title of "-KPZAOg58kUdqwYMzlDJ").
How do I get all the title's?
Use :-
rootRef.observeEventType(.Value, withBlock: {(postDictionary) in
if let postDict = postDictionary.value as? [String:AnyObject]{
for each in postDict as [String:AnyObject]{
let autoID = each.0
rootRef.child(autoID).observeEventType(.Value, withBlock: {(specificPost) in
//RETRIEVE YOUR DATA
})
}
}
})
PS:- I have used rootRef as you have not specified your parent nodes in your JSON structure :)

How to handle null response of web services

My app consuming PHP web services. But some field of response is null and i cant handle that null value.
This is my response
[
{
ID: 1,
ChapterID: 0,
Code: "FLGSV01",
Number: "0",
Text: "Swedish Flag",
VersionChanged: 1,
LastChange: "Jun 26 2013 12:00:00:000AM",
Type: "img",
info: null
}
]
I have parsed this response in my dictionary which like this
tmpDictn : {
ID = 1,
ChapterID = 1;
Code = SECH1W;
ID = 2;
LastChange = "Jun 26 2012 12:00:00:000AM";
Number = 001;
Text = "ett
\n";
Type = img;
VersionChanged = 1;
info = "<null>";
}
Now as you see value for info is Null and if i try to parse it in string than my string will be <null> but instead of this i just want it to display empty string.
I have tried this code but no luck
if ([tmpDictn objectForKey:#"info"]!=nil) {
info = [tmpDictn objectForKey:#"info"];
}
And this code gives me error of NSNull
if ([[tmpDictn objectForKey:#"info"] isEqualToString:#"<null>"]) {
info = [tmpDictn objectForKey:#"info"];
}
So how could i handle this null value?
Compare with [NSNull null]
From Docs
The NSNull class defines a singleton object used to represent null values in collection objects (which don’t allow nil values).
if([tmpDictn objectForKey:#"info"] == [NSNull null])
{
info = nil;
}
else
{
info = [tmpDictn objectForKey:#"info"]
}
info = [tmpDictn objectForKey:#"info"];
if(info == null)
{
//Handle null
}
if ([[tmpDictn objectForKey:#"info"] isKindOfClass:[NSNull class]])
{
info = [tmpDictn objectForKey:#"info"];
}
Try to use [NSNull null]
if ([tmpDictn objectForKey:#"info"]!=[NSNull null]) {
info = [tmpDictn objectForKey:#"info"];
} else {
//Handle null value
}

how to parse this in iphone

{
education = (
{
school = {
id = 108102169223234;
name = psss;
};
type = College;
year = {
id = 142833822398097;
name = 2010;
};
}
);
email = "amvijaycse#gmail.com";
"first_name" = Vijay;
gender = male;
id = 100000782204693;
"last_name" = Kumar;
link = "http://www.facebook.com/profile.php?id=100000782204693";
locale = "en_US";
location = {
id = 106377336067638;
name = "Bangalore, India";
};
name = "Vijay Kumar";
timezone = "5.5";
"updated_time" = "2010-11-21T07:45:11+0000";
}
i needed email,firstname,lastname.
[EDIT: Removed because it was inaccurate]

parse value from a dictionary/list

I have a dictionary/list balance_sign_dict from which I need to retrieve 2 values based on condition.
The source XML for this is;
<Value>
<Signature>-873</Signature>
<Amount>1501042000</Amount>
</Value>
I want to parse data from the dict shown below;
Could you please tell me how do I parse conditional data (e.g. if I want the value of "Amount" node for "Signature" node having -873) i.e. it should return me 1501042000
I want a generic way of parsing the values from the dictionary below.
Printing description of balance_sign_dict:
(
{
nodeChildArray = (
{
nodeContent = "-873";
nodeName = Signature;
},
{
nodeContent = 1501042000;
nodeName = Amount;
}
);
nodeName = Value;
},
{
nodeChildArray = (
{
nodeContent = "-1228";
nodeName = Signature;
},
{
nodeContent = 428586000;
nodeName = Amount;
}
);
nodeName = Value;
},
{
nodeChildArray = (
{
nodeContent = "-1140";
nodeName = Signature;
},
{
nodeContent = 79370000;
nodeName = Amount;
}
);
nodeName = Value;
},
Here is what I am trying now;
for (NSDictionary *valueNode in balance_sign_dict){
for (NSArray *nodeChildArray in [valueNode objectForKey:#"nodeChildArray"]){
NSString *tmpNodeName = [nodeChildArray objectAtIndex:1];
NSDictionary *tmpD = [valueNode objectAtIndex:1];
if ([tmpNodeName isEqualToString:#"Signature"]) {
tmpSignVal = [nodeChildArray objectAtIndex:0];
if ([tmpSignVal isEqualToString:#"-873"]) {
tmpSignAmt = [nodeChildArray objectAtIndex:1];
}
}
But for some reason the 2nd part of nodeChildArray gets removed...i.e. nodeContent = 1501042000;
nodeName = Amount;
I am not sure how to access that part.
Please help.
}
}
Actually here is what i get during alternate runs;
Printing description of nodeChildArray:
{type = mutable dict, count = 2,
entries =>
0 : {contents = "nodeName"} = {contents = "Signature"}
1 : {contents = "nodeContent"} = {contents = "-1507"}
}
Printing description of nodeChildArray:
{type = mutable dict, count = 2,
entries =>
0 : {contents = "nodeName"} = {contents = "Amount"}
1 : {contents = "nodeContent"} = {contents = "631000"}
}
How do I get the Amount value for matching Signature value?
NSArray and NSDictionary are the best container classes that I know of in any language that I am experienced with. NSDictionary can store any object or primitive, including an NSArray, and vice versa. When I say dictionary I am arbitrarily referring to either class.
When you output the description of any dictionary (which is as simple as NSLog(#"%#",myDict);, the entire contents of the dictionary are displayed like an XML (or maybe more accurately a JSON) document. It is easy to look at the content of the dictionary description to determine what is contained inside. () denotes an NSArray and {} denotes an NSDictionary.
// this is the beginning of an array.
(
// this is the beginning of index 0 of the array, an `NSDictionary`
{
// objectForKey:#"nodeChildArray"] isKindOfClass:[NSArray class]]
nodeChildArray = ( // inside nodeChildArray is another array
{ // index 0 of array is a dictionary with two keys
// objectForKey:#"nodeContent" == #"-873"
nodeContent = "-873";
// objectForKey:#"nodeName" == #"Signature"
nodeName = Signature;
}, // end of index 0
{ // index 1 of array
nodeContent = 1501042000;
nodeName = Amount;
} // end of index 1
); // end of nodeChildArray, an NSArray stored at objectForKey:#"nodeChildArray"
// this is the only other element in the dictionary, a string
// objectForKey:#"nodeName"] isKindOfClass:[NSString class]]
nodeName = Value;
}, // end of the dictionary containing nodeChildArray and nodeName
{ // objectAtIndex:1
nodeChildArray = (
{
nodeContent = "-1228";
nodeName = Signature;
},
{
nodeContent = 428586000;
nodeName = Amount;
}
);
nodeName = Value;
},
{ // objectAtIndex:2
nodeChildArray = (
{
nodeContent = "-1140";
nodeName = Signature;
},
{
nodeContent = 79370000;
nodeName = Amount;
}
);
nodeName = Value;
},
);
So you can see from looking at your NSDictionary debug output that it's actually an NSArray. The order of structures is NSArray->NSDictionary->NSArray->NSString <--> [[[[NSArray objectAtIndex:i] NSDictionary objectForKey:#"nodeChildArray"] NSArray objectAtIndex:j] NSDictionary objectForKey:#"nodeContent"], finally returning an NSString. Use this as the most recent code - in the last version of the code I passed balance_sign_dict as an NSDictionary. This might have even worked! But it is much better form to cast the argument properly. If you don't know whether or not your dictionary is going to start with an NSArray or an NSDictionary, you can cast it as an id and check its type with [theIdObject isKindOfClass:[{NSArray,NSDictionary} class]]. Don't use the {} and choose one of the two in your code.
-(NSDictionary*)parseBalance:(NSArray*)balance_sign_dict
{
NSMutableDictionary* theResults = [NSMutableDictionary dictionary];
for( NSDictionary* nodeDict in balance_sign_dict )
{
NSArray* nodeChildArray = [nodeDict objectForKey:#"nodeChildArray"];
[theResults addObject:[[nodeChildArray objectAtIndex:1] objectForKey:#"nodeContent"] forKey:[[nodeChildArray objectAtIndex:0] objectForKey:#"nodeContent"]];
}
return theResults;
}