Dictionary of dictionary - ios

Hi i am trying to create a dictionary (socialDict) inside a dictionary (dict) in ios at specified location (ios path) but it showing error i.e The data couldn’t be read because it isn’t in the correct format.
Code Snippet:
NSArray *arrayDirctories=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask,YES);
NSString *libraryPath=[arrayDirctories objectAtIndex:0];
NSString *filePath = [libraryPath stringByAppendingPathComponent:#"Hello/breaches.plist"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *socialDict = [[NSMutableDictionary alloc] init];
[socialDict setObject:arr forKey:#"count"];
[socialDict setObject:sitesArr forKey:#"sites"];
[socialDict setObject:timeArr forKey:#"time"];
[dict setObject:socialDict forKey:#"social"];
[dict writeToFile:filePath atomically:1];
Please can anyone find me way out through this. Thanks in advance.

but it worked for me..
NSArray*arr=[[NSArray alloc]initWithObjects:#"1",#"2",#"3", nil];
NSArray*sitesArr=[[NSArray alloc]initWithObjects:#"1",#"2",#"3", nil];
NSArray*timeArr=[[NSArray alloc]initWithObjects:#"1",#"2",#"3", nil];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *socialDict = [[NSMutableDictionary alloc] init];
[socialDict setObject:arr forKey:#"count"];
[socialDict setObject:sitesArr forKey:#"sites"];
[socialDict setObject:timeArr forKey:#"time"];
[dict setObject:socialDict forKey:#"social"];
// [dict setValuesForKeysWithDictionary:socialDict];
[dict writeToFile:filePath atomically:1];
the .plist file is

NSString *filePath = [libraryPath stringByAppendingPathComponent:#"file.plist"];
NSArray*arr1=[[NSArray alloc]initWithObjects:#"1",#"2",#"3", nil];
NSArray*arr2=[[NSArray alloc]initWithObjects:#"1",#"2",#"3", nil];
NSArray*arr3=[[NSArray alloc]initWithObjects:#"1",#"2",#"3", nil];
NSMutableDictionary *mainDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *subDict = [[NSMutableDictionary alloc] init];
[subDict setObject:arr forKey:#"count"];
[subDict setObject:sitesArr forKey:#"arr1"];
[subDict setObject:timeArr forKey:#"arr2"];
[mainDict setObject:subDict forKey:#"arr3"];
[mainDict writeToFile:filePath atomically:1];
It is working fine

Related

Create a record in Google contacts

I am trying to send a post request to create a record in Google contacts from my app and I am sending the "name" field in the request body as below.
-(void)exportGoogleContact:(NSString*)name {
CLNetworkDataModel *dataModel = [[CLNetworkDataModel alloc] init];
dataModel.httpMethod = eNetworkOperationTypePost;
NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
NSString *token = [data stringForKey:#"Accesstoken"];
NSLog(#"token is %#",token);
dataModel.apiUrl = [NSString stringWithFormat:#"https://people.googleapis.com/v1/people:createContact?access_token=%#",token];
NSString * requestString = [NSString stringWithFormat:#"name=%#",name];
dataModel.requestParams = requestString;
CLNetworkOperation *uuidOperation = [CLNetworkOperation operationForTarget:self callBackSelector:#selector(exportGoogleReponseData:)
dataModel:dataModel];
[[CLGlobalNetworkQueue sharedInstance] addOperation:uuidOperation];
}
I am getting the following error message:
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"name\":
Cannot bind query parameter. Field 'name' could not be found in
request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"name\": Cannot bind query parameter. Field 'name' could not be found in request message."
}
]
}
]
}
}
Anyone have idea, how to fix the this error, Thanks in advance
Here is the full code which is working fine for me
// Export to Google contacts
-(void)exportGoogleContact:(NSString*)name mobile:(NSString *)mobile phone:
(NSString *)phone email:(NSString*)email company:(NSString *)company
designation:
(NSString *)designation website:(NSString *)website address:(NSString
*)address
notes:(NSString*)notes {
CLNetworkDataModel *dataModel = [[CLNetworkDataModel alloc] init];
dataModel.httpMethod = eNetworkOperationTypePostJson;
NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
NSString *token = [data stringForKey:#"Accesstoken"];
NSLog(#"token is %#",token);
NSMutableDictionary * reqDict = [[NSMutableDictionary alloc] init];
[reqDict setObject:name forKey:#"Name"];
[reqDict setObject:mobile forKey:#"MobileValue"];
[reqDict setObject:phone forKey:#"PhoneValue"];
[reqDict setObject:email forKey:#"EmailValue"];
[reqDict setObject:company forKey:#"CompanyValue"];
[reqDict setObject:designation forKey:#"DesignasionValue"];
[reqDict setObject:website forKey:#"WebsiteValue"];
[reqDict setObject:address forKey:#"AddressValue"];
if([notes isEqual: #""]){
notes = #"Added through APPName";
}
[reqDict setObject:notes forKey:#"NotesValue"];
dataModel.apiUrl = [NSString
stringWithFormat:#"https://people.googleapis.com/v1/people:createContact?
access_token=%#",token];
//NSString * requestString = [NSString stringWithFormat:#"name=%#",name];
NSString *requestString = [CLUtils createJsonContentForGoogleSync:reqDict];
dataModel.requestParams = requestString;
CLNetworkOperation *uuidOperation = [CLNetworkOperation operationForTarget:self
callBackSelector:#selector(exportGoogleReponseData:)
dataModel:dataModel];
[[CLGlobalNetworkQueue sharedInstance] addOperation:uuidOperation];
}
//Here is the code to create json request
+ (NSString *) createJsonContentForGoogleSync:(NSDictionary *)reqDict{
NSMutableDictionary *phoneDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict2 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict3 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict4= [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict5 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *phoneDataDict6 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *companyDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *emailDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *designatioDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *websiteDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *nameDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *mobileDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *addressDataDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *notesDataDict = [[NSMutableDictionary alloc] init];
[nameDataDict setObject:[reqDict objectForKey:#"Name"] forKey:#"givenName"];
[websiteDataDict setObject:[reqDict objectForKey:#"WebsiteValue"]
forKey:#"value"];
//[designatioDataDict setObject:[reqDict objectForKey:#"DesignasionValue"]
forKey:#"value"];
[emailDataDict setObject:[reqDict objectForKey:#"EmailValue"] forKey:#"value"];
[designatioDataDict setObject:[reqDict objectForKey:#"DesignasionValue"]
forKey:#"title"];
[companyDataDict setObject:[reqDict objectForKey:#"CompanyValue"]
forKey:#"name"];
[mobileDataDict setObject:[reqDict objectForKey:#"MobileValue"]
forKey:#"value"];
[mobileDataDict setObject:#"mobile" forKey:#"type"];
[phoneDataDict setObject:[reqDict objectForKey:#"PhoneValue"] forKey:#"value"];
[phoneDataDict setObject:#"work" forKey:#"type"];
NSArray *companyArry;
if(![[companyDataDict objectForKey:#"name"] isEqual: #""]){
companyArry = [NSArray arrayWithObjects:companyDataDict,
designatioDataDict,nil];
}
else{
[companyDataDict setObject:#" " forKey:#"name"];
companyArry = [NSArray arrayWithObjects:companyDataDict,
designatioDataDict,nil];
}
NSArray *phoneNosArry;
phoneNosArry = [NSArray arrayWithObjects:mobileDataDict,phoneDataDict,nil];
if([reqDict.allKeys containsObject:#"PhoneValue2"]){
[phoneDataDict2 setObject:[reqDict objectForKey:#"PhoneValue2"]
forKey:#"value"];
[phoneDataDict2 setObject:#"work" forKey:#"type"];
phoneNosArry = [NSArray
arrayWithObjects:mobileDataDict,phoneDataDict,phoneDataDict2 ,nil];
}
if([reqDict.allKeys containsObject:#"PhoneValue3"]){
[phoneDataDict3 setObject:[reqDict objectForKey:#"PhoneValue3"]
forKey:#"value"];
[phoneDataDict3 setObject:#"work" forKey:#"type"];
phoneNosArry = [NSArray
arrayWithObjects:mobileDataDict,phoneDataDict,phoneDataDict2,phoneDataDict3
,nil];
}
if([reqDict.allKeys containsObject:#"PhoneValue4"]){
[phoneDataDict4 setObject:[reqDict objectForKey:#"PhoneValue4"]
forKey:#"value"];
[phoneDataDict4 setObject:#"work" forKey:#"type"];
phoneNosArry = [NSArray
}
if([reqDict.allKeys containsObject:#"PhoneValue5"]){
[phoneDataDict5 setObject:[reqDict objectForKey:#"PhoneValue5"]
forKey:#"value"];
[phoneDataDict5 setObject:#"work" forKey:#"type"];
phoneNosArry = [NSArray arrayWithObjects:mobileDataDict,phoneDataDict,phoneDataDict2,phoneDataDict3,phoneDataDict4,phoneDataDict5 ,nil];
}
if([reqDict.allKeys containsObject:#"PhoneValue6"]){
[phoneDataDict6 setObject:[reqDict objectForKey:#"PhoneValue6"] forKey:#"value"];
[phoneDataDict6 setObject:#"work" forKey:#"type"];
phoneNosArry = [NSArray arrayWithObjects:mobileDataDict,phoneDataDict,phoneDataDict2,phoneDataDict3,phoneDataDict4,phoneDataDict5,phoneDataDict6 ,nil];
}
//[phoneDataDict addEntriesFromDictionary:mobileDataDict];
[addressDataDict setObject:[reqDict objectForKey:#"AddressValue"] forKey:#"formattedValue"];
[notesDataDict setObject:[reqDict objectForKey:#"NotesValue"] forKey:#"value"];
[notesDataDict setObject:#"TEXT_PLAIN" forKey:#"contentType"];
NSMutableDictionary *parentDict = [[NSMutableDictionary alloc] init];
[parentDict setObject:nameDataDict forKey:#"names"];
[parentDict setObject:emailDataDict forKey:#"emailAddresses"];
[parentDict setObject:companyArry forKey:#"organizations"];
[parentDict setObject:websiteDataDict forKey:#"urls"];
// [parentDict setObject:designatioDataDict forKey:#"occupations"];
//[parentDict setObject:phoneDataDict forKey:#"phoneNumbers"];
[parentDict setObject:phoneNosArry forKey:#"phoneNumbers"];
//[parentDict setObject:mobileDataDict forKey:#"phoneNumbers"];
[parentDict setObject:addressDataDict forKey:#"addresses"];
[parentDict setObject:notesDataDict forKey:#"biographies"];
NSData *resultData = [NSJSONSerialization dataWithJSONObject:parentDict
options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString ;
if(resultData != nil){
jsonString = [[NSString alloc] initWithData:resultData
encoding:NSUTF8StringEncoding];
}
NSLog(#"####### Final json string is %#",jsonString);
return jsonString;
}

How can i create NSDictionary with multiple array of key and value

i tried to create static JSONArray of value in IOS using Objective -c
i want like this
tabledata={
["name":"image 1","path":"img1.jpg"],
["name":"image 2","path":"img2.jpg"],
["name":"image 3","path":"img3.jpg"],
["name":"image 4","path":"img4.jpg"],
["name":"image 5","path":"img5.jpg"],
["name":"image 6","path":"img6.jpg"],
["name":"image 7","path":"img7.jpg"]}
this is my data.. please help me any one how can i declare in objective-c..
You can create dictionary like below
NSDictionary *dict = #{
#"array": #[
#{
#"name":#"image 1",
#"path":#"img1.jpg"
},
#{
#"name":#"image 2",
#"path":#"img2.jpg"
}
....
]
};
and Array
NSArray *array = #[
#{
#"name":#"image 1",
#"path":#"img1.jpg"
},
#{
#"name":#"image 2",
#"path":#"img2.jpg"
}
....
];
For get value from NSDictionary
NSArray *array = NSDictionary[#"array"]
NSDictionary *firstObj = array[0];
NSString *name = firstObj[#"name"]
NSString *path = firstObj[#"path"]
from Array just
NSDictionary *firstObj = array[0];
NSString *name = firstObj[#"name"]
NSString *path = firstObj[#"path"]
One of the alternative old approach is:
NSMutableArray *tableData = [[NSMutableArray alloc] init];
NSMutableDictionary * dict1 = [[NSMutableDictionary alloc] init];
[dict1 setValue:#"image 1" forKey:#"name"];
[dict1 setValue:#"img1.jpg" forKey:#"path"];
NSMutableDictionary * dict2 = [[NSMutableDictionary alloc] init];
[dict2 setValue:#"image 2" forKey:#"name"];
[dict2 setValue:#"img2.jpg" forKey:#"path"];
NSMutableDictionary * dict3 = [[NSMutableDictionary alloc] init];
[dict3 setValue:#"image 3" forKey:#"name"];
[dict3 setValue:#"img3.jpg" forKey:#"path"];
[tableData addObject:dict1];
[tableData addObject:dict2];
[tableData addObject:dict3];
NSLog(#"%#",tableData);
//To Fetch Values
NSDictionary *dictionary1 = [tableData objectAtIndex:0];
NSLog(#"%#", [dictionary1 valueForKey:#"name"]);
You can make JsonString to NSDicitonary.
NSError *jsonError;
NSData *objectData = [#"{\"2\":\"3\"}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
and It is make NSDictionary with array.
- (NSDictionary *) indexKeyedDictionaryFromArray:(NSArray *)array
{
id objectInstance;
NSUInteger indexKey = 0U;
NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];
for (objectInstance in array)
[mutableDictionary setObject:objectInstance forKey:[NSNumber numberWithUnsignedInt:indexKey++]];
return (NSDictionary *)[mutableDictionary autorelease];
}

Creating NSDictionary

how i can create Dictionary that when i create jsondata with it, json looks like :
"historyStep":[
{
"counter": "50",
"timestamp": "1461674383632"
}
]
I did this :
NSMutableDictionary*jsonDictOth = [[NSMutableDictionary alloc]init];
[jsonDictOth setObject:#(810) forKey:#"counter"];
[jsonDictOth setObject:#"1464957395241.447998" forKey:#"timestamp"];
NSMutableDictionary *jsonDictMain = [[NSMutableDictionary alloc]initWithObjectsAndKeys:jsonDictOth,#"historyStep", nil];
NSError*error;
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDictMain
options:NSJSONWritingPrettyPrinted
error:&error];
but it looks :
historyStep = {
counter = 810;
timestamp = "1464957395241.447998";
};
You are missing a level: NSDictionary (top level) with NSArray of NSDictionary in the top level key historyStep:
NSMutableDictionary *topLevel = [[NSMutableDictionary alloc] init];
NSArray *historySteps = [[NSMutableArray alloc] init];
//Here you may have a for loop in case there are more steps
NSDictionary *aStep = #{#"counter":#"50", #"timestamp":#"1461674383632"};
[historySteps addObject:aStep]
[topLevel setObject:historySteps forKey#"historyStep"];
NSError*error;
NSData *data = [NSJSONSerialization dataWithJSONObject:topLevel
options:NSJSONWritingPrettyPrinted
error:&error];
NSDictionary *innerDictionary = [[NSDictionary alloc]initWithObjectsAndKeys:#"50", #"counter",#"1461674383632", #"timestamp", nil];
NSArray *array = [[NSArray alloc]initWithObjects:innerDictionary, nil];
NSDictionary *outerDict = [[NSDictionary alloc]initWithObjectsAndKeys:array, #"historyStep", nil];
Use this code it will work perfectly.
Your code should be like,
NSMutableDictionary*jsonDictOth = [[NSMutableDictionary alloc]init];
[jsonDictOth setObject:#(810) forKey:#"counter"];
[jsonDictOth setObject:#"1464957395241.447998" forKey:#"timestamp"];
NSMutableArray *arr = [[NSMutableArray alloc]init];
[arr addObject:jsonDictOth];
NSMutableDictionary *jsonDictMain = [[NSMutableDictionary alloc]initWithObjectsAndKeys:arr,#"historyStep", nil];
NSLog(#"jsonMain is %#",jsonDictMain);
NSError*error;
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDictMain
options:0
error:&error];
It's output is,
jsonMain is {
historyStep = (
{
counter = 810;
timestamp = "1464957395241.447998";
}
);
}
You just missed one array between

Sort array with dictionaries by date

I have an NSArray with NSDictionary inside. It looks like:
etc.
I need to sort it by date inside NSDictionary. I need something like this:
How can I do this? Here is my method which gives me first unsorted array:
- (void)iterateOverDocumentsDirectory
{
arrayWithFiles = [NSMutableArray new];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirPath = [paths objectAtIndex:0];
NSString *finalPathToFolder = [NSString stringWithFormat:#"%#/", documentsDirPath];
albumNames = [[fileManager contentsOfDirectoryAtPath:finalPathToFolder error:&error] mutableCopy];
if (albumNames == nil) {
// error...
}
for (NSString *album in albumNames)
{
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:album forKey:#"name"];
NSString *finalPathToFiles = [NSString stringWithFormat:#"%#/%#", documentsDirPath, album];
NSArray *tempArray = [fileManager contentsOfDirectoryAtPath:finalPathToFiles error:&error];
NSMutableArray *arrayWithEachFiles = [NSMutableArray new];
for (NSString *tempString in tempArray)
{
NSMutableDictionary *eachFileDict = [[NSMutableDictionary alloc] init];
NSString *pathToFile = [NSString stringWithFormat:#"%#/%#/%#", documentsDirPath, album, tempString];
[eachFileDict setValue:pathToFile forKey:#"path"];
NSDictionary *filePathsArray1 = [[NSFileManager defaultManager] attributesOfItemAtPath:pathToFile error:nil];
NSDate *modifiedDate = [filePathsArray1 objectForKey:NSFileCreationDate];
[eachFileDict setValue:modifiedDate forKey:#"date"];
[arrayWithEachFiles addObject:eachFileDict];
}
NSSortDescriptor *ageDescriptor = [[NSSortDescriptor alloc] initWithKey:#"date" ascending:YES];
NSArray *sortDescriptors = #[ageDescriptor];
NSArray *sortedArrayWithFiles = [[arrayWithEachFiles sortedArrayUsingDescriptors:sortDescriptors] mutableCopy];
[tempDict setValue:sortedArrayWithFiles forKey:#"files"];
[arrayWithFiles addObject:tempDict];
}
}
Use following code for sorting the array of dictionaries:
NSArray * sortedArray = [myArray sortedArrayUsingComparator:^(id obj1, id obj2) {
NSNumber *rating1 = [(NSDictionary *)obj1 objectForKey:#"date"];
NSNumber *rating2 = [(NSDictionary *)obj2 objectForKey:#"date"];
return [rating1 compare:rating2];
}];
You can sort it easily by using sortArrayUsingComparator:
[array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return //pseudo-code: {obj1->dict->date isLaterThan obj2->dict->date};
}];
I sort it. Not sure that my code is clear and well optimized. But here is a solution:
NSMutableArray *masterArray = [NSMutableArray new];
NSMutableArray *sameDates = [NSMutableArray new];
BOOL started = NO;
NSString *prevDate;
for (NSDictionary *dict in sortedArrayWithFiles)
{
NSString *tempString = [dict objectForKey:#"date"];
if (started)
{
if ([tempString isEqualToString:prevDate])
{
[sameDates addObject:dict];
}
else
{
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:tempString forKey:tempString];
[tempDict setValue:sameDates forKey:#"files"];
[masterArray addObject:tempDict];
prevDate = tempString;
[sameDates removeAllObjects];
[sameDates addObject:tempString];
}
}
else
{
// first element
started = YES;
prevDate = tempString;
[sameDates addObject:dict];
}
}
// last value
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:prevDate forKey:prevDate];
[tempDict setValue:sameDates forKey:#"files"];
[masterArray addObject:tempDict];
In master array we store array with dictionaries separated by date.

Access to coordinates through NSDictionary - iOS

I would like to access coordinate values which are latitude and longitude.
NSString *path = [[NSBundle mainBundle] pathForResource:
#"WellList" ofType:#"plist"];
NSMutableArray *cities = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSDictionary *routes =[[NSDictionary alloc]initWithContentsOfFile:path];
NSDictionary *city =[[NSDictionary alloc]init];
NSDictionary *locations =[[NSDictionary alloc]init];
NSDictionary *locationInfo=[[NSDictionary alloc]init];
NSMutableArray *localCities= [[NSMutableArray alloc]init];
city= routes [#"Routes"];
NSLog (#"%#",city);
localCities =[[NSMutableArray alloc] initWithArray:[city allValues]];
locations =[localCities objectAtIndex:1];
I think your problem is that you don't understand how loading a .plist file works. Routes and Cities are being initialized to the same value, because you are loading both of them from the same file. So to access the latitude of Houston's Location 1, you would write
NSMutableDictionary *root = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
NSString* latitude = [[[[[root objectForKey: #"Routes"] objectForKey: #"Houston" ] objectForKey: #"Location 1"] objectForKey: #"coordinate"] objectForKey: #"latitude"];

Resources