-5

I'm currently building an food tracker iOS app (using swift 2) and I would like to have a database with all the foods (and their info) stored in the app and accessible.

The idea is that when some add a 'ice cream' to their meal, his calories/sugar/fat 'counters' increase by the respective nutritional value of the ice cream. (so that this data can be processed later on)

I have found a database of food in what seems like JSON format (see bellow) but I have no idea how to process all this data with swift so that I could access the number of calories in a specific ingredient for example.

So far I tried this:

    let url = NSURL(string: "myURL")

    let session = NSURLSession.sharedSession()

    let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in

        if error != nil {

            print(error)

        } else {


              let jsonResult = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary


                print(jsonResult)
        }      
    })

    task.resume()
}

It allows me to process the JSON format into a dictionary that I can access but what I need (I think) would be maybe a dictionary of arrays and I can't manage to make it work with the JSON format that I have bellow.

    [
      {
        "Description": "Juice",
        "Energy(kcal)Per 100 g": 29,
      },
      {
        "Description": "Alcoholic beverage, daiquiri, canned",
        "Energy(kcal)Per 100 g": 125,
      }
        ...
    ]

I admit my question wasn't quite clear at first (I'm really new at this I apologize) but I actually tried to research it on Stackoverflow before posting, but I haven't find something that works for my case. Sorry again and many thank you for taking the time to still answer it :)

3 Answers3

0

Have a look into NSJSONSerialization. That is what you get for free once installed xcode and the SDK. And it is not that bad actually.

This is Ray's approach to Swifty Json: http://www.raywenderlich.com/82706/working-with-json-in-swift-tutorial

This is what you find when you use the search. You will have to "translate" it to swift though. How do I parse JSON with Objective-C?

You may want to look at RestKit for some more convenient way of dealing with JSON sources.

Give it a try. And when you run into concrete problems, then get back to SO.

Community
  • 1
  • 1
Hermann Klecker
  • 14,039
  • 5
  • 48
  • 71
-1

Answer for reference pruposes. How to do this in Objective-C

1- First get the info

a) If you are getting the JSON from an API or any online site:

//Set url of the JSON
NString *urlReq = @"http://www.URLHERE.com/PATH/TO/THE/JSON"

//Get data from the JSON
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlReq]];

//Parse JSON
if(jsonData != nil){ //If the response is nil, the next line will crash
    NSArray *resultArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    //Do stuff with the result...
}

b) If you are getting the information from the Core Data:

//Get context
NSManagedObjectContext *context = [self managedObjectContext];

//Preapre your fetch
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Products" inManagedObjectContext:context];
NSFetchRequest *requestCoreData = [[NSFetchRequest alloc] init];
[requestCoreData setEntity:entityDescription];
//add predicates if needed

//Execute fetch
NSArray *resultArray = [context executeFetchRequest:requestCoreData error:nil];

//do stuff with the result....

2- Then parse the retrieved info

a) If you want a specific index:

NSString *description = resultArray[0][@"description"];

b) if you don't know what is the index you want (most likely what happens in your JSON):

BOOL found = NO;
int index = 0;
while(index < [resultArray count] && !found){
    if([resultArray[index][@"description"] isEqualToString:@"Juice"])
        found = YES;
    else
        ++index;
}

if(found){
    //'index' => index where the info you are searching can be found
}
else{
    //The info couldn't be found in the array
}
-1

Just give it a try

var arrDicts: [Dictionary<String, AnyObject>] = []
arrDicts = try! NSJSONSerialization.JSONObjectWithData(dataFromService!, options: NSJSONReadingOptions.AllowFragments) as! [Dictionary<String, AnyObject>]

dataFromService is the data that you have received from web service.

channi
  • 1,028
  • 9
  • 16