Retrieving entire collection then add it into a dictionary - objcmongodb

I can retrieve a single entry from a collection in a mongodb but I cannot retrieve the entire collection. After I retrieve the entire collection I would like to put it into a dictionary. Retrieving the entire collection should be simple. I have tested the various commands I would use in the shell to accomplish the task, but all are unsuccessful once translated into objective-c.
//Message Retrieval
BSONDocument *resultDoc = [collection findAllWithError:&error];
NSDictionary *result = [BSONDecoder decodeDictionaryWithDocument:resultDoc];
NSLog(#"fetch result: %#", result);

-findAllWithError: returns an array of documents:
NSArray *results = [collection findAllWithError:&error];
for (BSONDocument *resultDoc in results) {
NSDictionary *result = [BSONDecoder decodeDictionaryWithDocument:resultDoc];
NSLog(#"fetch result: %#", result);
}

Related

Trouble loading data for TableView from server

Im using a web-service API to load information from a DB (mySQL). When transitioning to a UITableViewController, I retrieve an array that contains categories in the VieDidLoad method. However, I am not able to display the array of categories that I got into the table view cells. When I init the category NSMutubaleArray and hardcode it on the otherhand, the tableview does display the information. I am trying to understand what I'm doing wrong in the steps of loading this array and populating it onto the tableview. Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
//When I init the _categoryList the way below, it displays the info.
//_categoryList = [[NSMutableArray alloc] initWithObjects:#"Trending",#"Sports",#"Portraits", #"Art",#"IdUser", nil];
_toCategory = [[NSString alloc]init];
//When I try to populate it from the server it doesnt work.
_categoryList = [[NSMutableArray alloc]init];
//just call the "getCategories" command from the web API
[[API sharedInstance] commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:
#"getCategories",#"command",
nil]
onCompletion:^(NSDictionary *json) {
//got stream
NSArray *tempArray = [json objectForKey:#"result"];
for (int i=0;i<tempArray.count;i++){
[_categoryList insertObject:[tempArray objectAtIndex:i] atIndex:i];
}
//I verify that I was able to retrieve the array with the correct conent.
[self printArray:_categoryList];
NSLog(#"got categories");
[self.tableView reloadData];
}];
}
Any help would be greatly appreciated. Thanks!
UPDATE #1:
The JSON return is an array with NSDictioanry's. I print out its contents just to make sure, by calling the JsonArray objectForKey[‘categories’] and get this:
SwiphtMVPClone[2410:11303] Array at Index 0 = Trending
SwiphtMVPClone[2410:11303] Array at Index 1 = Sports
SwiphtMVPClone[2410:11303] Array at Index 2 = Portraits
SwiphtMVPClone[2410:11303] Array at Index 3 = Art
Right now, my app is actually crashing – getting this error:
[__NSCFDictionary isEqualToString:]: unrecognized selector sent to instance 0x72a85d0

Fast Enumeration in parse

I'm new to iOS and I'm trying to parse out JSON data. Nothing will log from inside of the enumeration, though vehicleActivity logs "vehicle (null).I am interested in logging the "LineRef" data. I'm assuming it is in NSString, but I tried with id object and still nothing.
NSDictionary *jsonParse = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSArray * vehicleActivity = [jsonParse objectForKey:#"VechicleActivity"];
NSLog(#"vehicle %#",vehicleActivity);
for (NSDictionary *dictionary in vehicleActivity ) {
NSDictionary *monitoredVehJourney = [dictionary objectForKey:#"MonitoredVehicleJourney"];
NSString *line = [monitoredVehJourney objectForKey:#"LineRef"];
NSLog(#"Line # %#",line);
Here is the JSON through a viewer
Thanks
though vehicleActivity logs "vehicle (null)"
That's why. If vehicleActivity is NULL (i. e., nil), then the fast enumeration wouldn't even begin.
Furthermore, you seem not to have read the documentation of the NSDictionary class. It iterates through keys, not values. So your for loop should be
for (NSString *key in vehicleActivity ) {
NSDictionary *dictionary = [vehicleActivity objectForKey:key];
// etc.
}
instead.
Furthermore, I believe you have a typo in your code regarding the key VehicleActivity. You wrote it as VechicleActivity.

Understanding xcode json web request

this is my first time connecting an app to the web, I just want to make sure i am clear on how this works.
I want to download data from a mysql db hosted online, it also seems to have php attached (hostgator) is the host.
So steps are:
1. In php (on the server module), set up a method to transcribe mysql information into JSON using the attached PHP module. Return an array (json i think is a mutilayered dictionary array object)
In xcode, use apple's json framework to create a url request, and download data into a json object (or array or dictionary?
Go through the data and create objects and save to coredata.
Please let me know if im following the logic correctly.
Also does JSON return 1 object or all the objects on the mysql db. So if i need to input 10,000 objects on coredata i have to make 10,000 requests or one request and parse 10,000 objects worth of info?
Also is this the best way to do what i need to do? I have heard of http request but it seems complicated, and I have no clue what it is.
Sorry for such a noob question.
Thanks for the help.
There are many ways to do it, some are "more correct" than others :-) but you are on the right way.
I explain what I would do in a similar situation:
1- for the PHP engine, you should create an API to access your data. Which data?
The simpliest and probably the first thing you can do TO TEST (only for testing purpose!!!!) is to create a page that receive a query via POST from your ios APP and answer with an encoded JSON string. With JSON you can transfer an entire hierarchy of objects: variables, arrays, dictionary...is up to you to decide how link the objects together.
If the data you want to encode is a table, you can do something similar to this:
// first connect to the database and execute the query, then...
$data = array();
while(!$RS->EOF){
for ($i = 0; $i < $cols; $i++){
$rowName = utf8_encode($RS->Fields[$i]->name);
$rowValue = utf8_encode($RS->Fields[$i]->value);
$rowData[$rowName] = $rowValue;
}
array_push($data, $rowData);
$RS->MoveNext();
}
$response['data'] = $data;
echo json_encode($response);
the result is a JSON object with a first dictionary with a key named "data".
Inside the "data" key there is an array of dictionaries. Each dictionary has the column name for the key, and the column value for the data:
data = (
{
attivita = "this is the first row in the table";
id = 2548;
},
{
attivita = "this is the second row in the table";
id = 2547;
};
}
You can simply use json_encode to create your json string.
On the iPhone side, I suggest you to download and use AFNetworking. It's a very good and complete open source framework, with a lot of builtin objects and methods for http/https requests, XML, JSON ecc...
Using AFNetworking you can make the request in a similar way:
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:#"http://url.for.the.php.page"];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:mainPath parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// your success code here
// remember, the first object is a dictionary with a key called data
NSArray *arrayOfData = [JSON objectForKey:#"data"];
NSMutableArray *arrayOfActivities = [NSMutableArray array];
for (NSDictionary *objectDictionary in arrayOfData) {
// objectDictionary is your dictionary containing
// a key with the column name and a value with the column content
// here you can init your custom objects
}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
// your failure code here
}];
[operation start];
As you can see, the JSONRequestOperationWithRequest: method has a completion handler returning you the decoded JSON, so you can access your dictionaries/arrays directly using objectForKey or objectAtIndex ;-)
Last suggestions: in a production and secure environment, you should avoid sending query over post requests. The code I pasted here is for a private application (used only by me for testing purpose). It's better to use a different API for each kind of request and a secure authentication method (look at oAuth).
I suggest you to give a look to the Instagram or Twitter API (Instagram is simpler), trying to use it. They will give you some ideas on how to create your own API.
Good luck
Your first step of creating a method to return JSON-ified MySQL data is correct. What exactly is returned however, is completely up to you! You will find that JSON is an extremely flexible format that allows you to put nearly any format of data in your response. It may make sense, depending on what you want to do, to have several methods in your PHP module that return different things. For example, if you have a database of books, maybe you want to create a method that allows you to specify an author, and will return a JSON response with all the books in your database written by that author.
You could use HttpRequest to actually perform the call to your module, but I found the Obj-C NSURLRequest quite easy to use:
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:#"http://yoururl/books/38917"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
Don't think that you have to manually parse the JSON response into your own Objective-C objects; this is a very common task and there exist many great libraries to do so. Check out this tutorial on the SBJSON framework to view one of the most popular solutions.
As an example, here is how you could parse the JSON response into an NSDictionary for easy traversal:
// Create SBJSON object to parse JSON
SBJSON *parser = [[SBJSON alloc] init];
// parse the JSON string into an object - assuming json_string is a NSString of JSON data
NSDictionary *object = [parser objectWithString:json_string error:nil];

How to extract app information from the Apple store?

I'm a newbie with Json, so I want to extract some app information from the app store, I found this question here :
How to get info from the Apple iTunes «App Store» and «Mac App Store»
It allows to get a Json file containing all the app information, but it would be nice if someone could show me how to get the price for example.
Thanks.
Where and how do you want to collect the results? Is this for an app or for some other kind of tool? In the reuslting JSON you have an array "results" where each element has a "currency" and a "price" value. Those can be queired rather simply. For example using the iOS 5 NSJSONSerialization (note this is an example, there has to be more error handling, handling of no / too many entries etc):
// assuming you have the downloaded data
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:downloadedData options:nil error:&error];
if (error != nil)
{
// error handling
}
else
{
NSArray *results = [jsonData objectForKey:#"results"];
// assuming you have 1 valid entry
NSDictionary *result = [results objectAtIndex:0];
NSNumber *price = [result objectForKey:#"price"];
NSString *currency = [result objectForKey:#"currency"];
NSLog(#"Price is %# #%", price, currency);
}
Similar ways to access the data are avilable in other JSON frameworks, just grad the results array and every dictionary therein has a price and currency value.

How do you parse a JSON array with TouchJSON?

I'm using TouchJSON. Made a call to my Rails app to fetch all "posts" at localhost:3000/posts.json. This returns a JSON array, surrounded by square brackets. I'm currently set up to convert the jsonString into an NSDictionary, but that fails due to the square brackets.
NSString *jsonString=[self jsonFromURLString:#"http://localhost:3000/posts.json"];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
self.dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
What's the best way to turn this result into an NSArray using the TouchJSON library?
Error Domain=kJSONScannerErrorDomain Code=-101 "Could not scan dictionary. Dictionary that does not start with '{' character."
Why don't you just use the -deserialize: method and then figure out what kind of object you have after its done?
Or to answer your specific question, use -deserializeAsArray:
I think most parsers frown with array data. You'll have to return a hash:
{'result': [Your array data]}