Guest User

Untitled

a guest
Dec 17th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. -(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
  2. //get string from searchBar textfield
  3. NSString* searched = self.searchBar.text;
  4.  
  5. //format the API call to search for the "searched" item (%@ after 'search/')
  6. NSString* formattedURL = [NSString stringWithFormat:@"https://api.nutritionix.com/v1_1/search/%@?results=0:100&fields=item_name,nf_total_fat,nf_protein,nf_total_carbohydrate&appId=f35a80a7&appKey=9263d4b1c216becb04681b1cd04d1815",searched];
  7.  
  8. dispatch_async(dispatch_get_main_queue(), ^{
  9. [[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:formattedURL] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  10.  
  11. NSDictionary* foodsFoundDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
  12.  
  13. //array holds an array of all the foods found from the API call
  14. NSArray* array;
  15. array = [foodsFoundDict valueForKey:@"hits"];
  16.  
  17. //since the info needed is inside the dictionary @"fields" of each array element, loop through array and add each dictionary to the global searchedFoodsArray
  18. for(NSDictionary* dict in array){
  19. [self.searchedFoodsArray addObject:dict[@"fields"]];
  20. }
  21. }]resume];
  22. [self.tableView reloadData];
  23.  
  24. });
Add Comment
Please, Sign In to add comment