Today's Menu  Portugal
journal and plan nutrition
V7USDAdataViewController.m
Go to the documentation of this file.
1 //
2 // V7USDAdataViewController.m
3 // TodaysMenu
4 //
5 // Created by Don Zeek on 6/17/18.
6 // Copyright © 2018 net.dzeek.y2015.ios.portfolio. All rights reserved.
7 //
8 
10 #import "Z5DataController.h"
11 #import "V7UsdaFoodsTableView.h"
14 #import "V7foodTextFieldView.h"
15 
16 @interface V7USDAdataViewController ()
17 
18 @end
19 
20 @implementation V7USDAdataViewController
21 {
22  NSMutableArray<NSDictionary *> *usdaFoodItems;
23  CGRect foodEntriesTableFrame;
26  NSString *searchFood;
27 }
28 - (void)viewDidLoad {
29  [super viewDidLoad];
30  // Do any additional setup after loading the view.
31  self.title = @"USDA List";
32  CGRect totalFrame = self.view.frame;
33 
34  // get and scale image for background
35  UIImage *backgrdImage = [UIImage imageNamed:@"antiqueSunburstWood.png"];
36  CGSize photoSize = [backgrdImage size];
37  float resizeRatio = photoSize.height / totalFrame.size.height;
38  UIImage *resizedImage = [UIImage imageWithCGImage:[backgrdImage CGImage]
39  scale:backgrdImage.scale * resizeRatio
40  orientation:(backgrdImage.imageOrientation) ];
41  UIImageView *backgrd = [[UIImageView alloc] initWithImage:resizedImage];
42  [self.view addSubview:backgrd];
43  // end - get and scale image for background
44 
45  usdaFoodItems = [[NSMutableArray alloc] init];
46  foodEntriesTableFrame = CGRectMake(totalFrame.size.width * 0.04,
47  totalFrame.size.height * 0.12,
48  totalFrame.size.width * 0.92,
49  totalFrame.size.height * 0.86);
50  headerView = [[V7foodTextFieldView alloc] initWithDelegate:self];
51 
52  foodEntriesTableView = [[V7UsdaFoodsTableView alloc] initWithFrame:foodEntriesTableFrame andHeader:headerView inContainer:self];
53  [foodEntriesTableView setDataSource:self];
54  [foodEntriesTableView setDelegate:self];
55 
56 // [_foodEntriesTableView setViewForHead:headerView];
57  [foodEntriesTableView setBackgroundColor:[[Z5DataController sharedInstance] wheatColor]];
58  [self.view addSubview:foodEntriesTableView];
59 
60 }
61  -(void) viewWillAppear:(BOOL)animated
62 {
63  [headerView appear:self.view.frame];
64 }
65 
67 {
68  Z5URLSessionController *sessionController = [[[Z5DataController sharedInstance] remoteDataController] sessionController];
69 
70  // Create the request.
71  // NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
72 
73 // NSString *searchStr = @"https://api.nal.usda.gov/ndb/search/?format=json&q=";
74 // NSArray<NSString *> *listItems = [searchFood componentsSeparatedByString:@", "];
75 // for (NSString *foodSpec in listItems) {
76 // NSString *foodSpecQuery = [NSString stringWithFormat:@"%@%%20",foodSpec];
77 // searchStr = [searchStr stringByAppendingString:foodSpecQuery];
78 // }
79 // searchStr = [searchStr stringByAppendingString:@"sort=n&max=25&offset=0&api_key=MHeHC2wqKJHmMxYqHzzLlMfnl4ZOLQLAZeKGEkdK"];
80 
81  searchFood = [searchFood stringByReplacingOccurrencesOfString:@", " withString:@"+"];
82  NSString *searchStr = [NSString stringWithFormat:@"https://api.nal.usda.gov/ndb/search/?format=json&q=%@&sort=n&max=25&offset=0&api_key=MHeHC2wqKJHmMxYqHzzLlMfnl4ZOLQLAZeKGEkdK", searchFood];
83 
84  NSLog(@"V7USDAdataViewController.hitScanDatabase: searchStr: %@", searchStr);
85  [headerView showUSDAFoodDatabaseResponse:USDAFoodDatabaseQueried];
86  NSURL *searchURL = [NSURL URLWithString:searchStr];
87  NSURLRequest *request = [NSURLRequest requestWithURL:searchURL];
88 
89  [sessionController fetchUSDAdata: request withCompletionBlock: ^(NSDictionary *informationDictionary, NSError *error) {
90  if (!error) {
91  // NSLog(@"V7USDAdataViewController.viewWillAppear: USDA-data %@", informationDictionary);
92  [self->headerView showUSDAFoodDatabaseResponse:USDAFoodDatabaseRespOK];
93 
94  NSDictionary *foodList = [informationDictionary objectForKey:@"list"];
95  assert(foodList);
96 
97  NSArray *foodItems = [foodList objectForKey:@"item"];
98  assert(foodItems);
99 
100  NSInteger nFoodItems = [foodItems count];
101  NSLog(@"V7USDAdataViewController.viewWillAppear: nFoodItems: %ld", (long)nFoodItems);
102 
103  [self->usdaFoodItems removeAllObjects];
104  [self->usdaFoodItems addObjectsFromArray:foodItems];
105  [self reframeTable];
106 
107  }
108  else
109  {
110  [[NSOperationQueue mainQueue] addOperationWithBlock:^{
111  // [NSApp presentError:error];
112  [self->headerView showUSDAFoodDatabaseResponse:USDAFoodDatabaseRespErr];
113  NSLog(@"USDADataView.viewWillAppear: Error: %@", error);
114  }];
115  }
116  }];
117 }
118 
122 - (void) reframeTable
123 {
124  CGRect totalFrame = self.view.frame;
125  float foodsTableHeight = 0.0;
126  CGRect topNaviFrame = [[[self navigationController] navigationBar] frame];
127  float availableWindowTop = topNaviFrame.origin.y + topNaviFrame.size.height;
128 
129  if (0 < [usdaFoodItems count]) {
130  foodsTableHeight = [foodEntriesTableView getViewHeightReqmt]
131  + 42.0 * [self assessFoodsToDisplay];
132  float maxHgt = totalFrame.size.height * 0.80;
133  if (maxHgt < foodsTableHeight) {
134  foodsTableHeight = maxHgt;
135  }
136  }
137  foodEntriesTableFrame = CGRectMake(totalFrame.size.width * 0.04,
138  availableWindowTop + totalFrame.size.height * 0.04,
139  totalFrame.size.width * 0.92,
140  foodsTableHeight);
141  [foodEntriesTableView setFrame:foodEntriesTableFrame];
142 
143  [self.view setNeedsDisplay];
144  [foodEntriesTableView reloadData];
145 }
146 - (NSInteger) assessFoodsToDisplay
147 {
148  NSInteger ret = [usdaFoodItems count];
149 
150  NSLog(@"USDAdataViewController.assessMessagesToDisplay: ret: %ld", (long)ret);
151  return ret;
152 }
153 
154 #pragma mark - V7foodTextFieldDelegate
155 
156 - (void) clickScan
157 {
158  UITextField *searchFoodtextF = [headerView foodTextField];
159  searchFood = [searchFoodtextF text];
160  if (nil!=searchFood) {
161  [self hitScanDatabase];
162  } else {
163  NSLog(@"USDAdataViewController.clickScan: no search food");
164  }
165 }
166 
167 #pragma mark - UITableView Delegate Methods
168 
169 - (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
170  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"usda-items"];
171  // NSLog(@"GmailView.cellForRow: cell: %@", cell);
172  if (cell == nil) {
173  cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"usda-items"];
174 
175  cell.contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
176  [cell.layer setCornerRadius:7.0f];
177  [cell.layer setMasksToBounds:YES];
178  [cell.layer setBorderWidth:1.0f];
179 
180  CGRect contentRect = [cell.contentView frame];
181  CGRect fetchPublishButton1Frame = CGRectMake(contentRect.size.width - 86.0f, 5.0, 34.0f, contentRect.size.height - 10);
182  UIButton *pushMe = [[UIButton alloc] initWithFrame:fetchPublishButton1Frame];
183  [pushMe setTitle:@"GO" forState:UIControlStateApplication];
184 
185  [cell.contentView addSubview:pushMe];
186  [cell setHidden:NO];
187  }
188 
189  NSInteger nFoodItems = [usdaFoodItems count];
190  NSInteger iRow = [indexPath row];
191  if (nFoodItems > iRow) {
192  NSDictionary *foodItem = [usdaFoodItems objectAtIndex:iRow];
193  NSString *caption = [foodItem objectForKey:@"name"];
194 
195  // cell.textLabel.text = caption;
196  [Z5DataController labelizeCell:cell withText:caption inColor:[UIColor lightGrayColor] andDetail:@"detailed"];
197  // [cell setBackgroundColor:[UIColor colorWithHue:0.18f saturation:1.0f brightness:0.6f alpha:0.4f]];
198  }
199 
200  return cell;
201 }
202 
203 - (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
204  return [usdaFoodItems count];
205 }
206 #pragma mark - Table view delegate
207 
212 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
213  int row = (int)[indexPath row];
214 
215  NSDictionary *focusFoodItem = [usdaFoodItems objectAtIndex:row];
216 
217  NSString *focusFoodName = [focusFoodItem objectForKey:@"name"];
218  NSLog(@"GmailViewController.didSelectRow: food: %@", focusFoodName);
219  NSNumber *ndbNumber = [focusFoodItem objectForKey:@"ndbno"];
220 
222  [vc2 setFocusFoodItemNDB:ndbNumber];
223  [vc2 setFocusFoodName:focusFoodName];
224  [[self navigationController] pushViewController:vc2 animated:YES];
225 }
226 #pragma mark - V7UsdaFoods table delegate
227 - (NSMutableArray<NSDictionary *> *) retrieveFoodEntries
228 {
229  return usdaFoodItems;
230 }
231 #pragma mark - NSURLConnection Delegate Methods
232 
233 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
234  // A response has been received, this is where we initialize the instance var you created
235  // so that we can append data to it in the didReceiveData method
236  // Furthermore, this method is called each time there is a redirect so reinitializing it
237  // also serves to clear it
238  _responseData = [[NSMutableData alloc] init];
239 }
240 
241 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
242  // Append the new data to the instance variable you declared
243  [_responseData appendData:data];
244 }
245 
246 - (NSCachedURLResponse *)connection:(NSURLConnection *)connection
247  willCacheResponse:(NSCachedURLResponse*)cachedResponse {
248  // Return nil to indicate not necessary to store a cached response for this connection
249  return nil;
250 }
251 
252 - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
253  // The request is complete and data has been received
254  // You can parse the stuff in your instance variable now
255 
256 }
257 
258 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
259  // The request has failed for some reason!
260  // Check the error var
261 }
262 
263 
265  [super didReceiveMemoryWarning];
266  // Dispose of any resources that can be recreated.
267 }
268 
269 /*
270 #pragma mark - Navigation
271 
272 // In a storyboard-based application, you will often want to do a little preparation before navigation
273 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
274  // Get the new view controller using [segue destinationViewController].
275  // Pass the selected object to the new view controller.
276 }
277 */
278 
279 #pragma mark END
280 
281 @end
NSString * searchFood
instancetype sharedInstance()
NSMutableArray< NSDictionary *> * retrieveFoodEntries()
V7foodTextFieldView * headerView
void fetchUSDAdata:withCompletionBlock:(NSURLRequest *request, [withCompletionBlock] void(^ incomingDictionary)(NSDictionary *informationDictionary, NSError *error))
CGRect foodEntriesTableFrame
Singleton interface to both core and remote data sources.
V7UsdaFoodsTableView * foodEntriesTableView
void labelizeCell:withText:inColor:andDetail:(UITableViewCell *targCell, [withText] NSString *txt, [inColor] UIColor *color, [andDetail] NSString *detailTxt)