Advertisement
Guest User

coffee

a guest
Apr 5th, 2014
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //
  2. //  TableViewController.m
  3. //  foursquareRequests
  4. //
  5. //  Created by Steven Palomino on 3/15/14.
  6. //  Copyright (c) 2014 Steven Palomino Design. All rights reserved.
  7. //
  8.  
  9. #import "TableViewController.h"
  10. #import "AFNetworking.h"
  11. #import "CustomObject.h"
  12. #import "DetailCellViewController.h"
  13. #import "AllBusinessesViewController.h"
  14. #import "VenuesTableViewCell.h"
  15. #import "UIImageView+WebCache.h"
  16. #import "MBProgressHUD.h"
  17. #import "VenuesTableViewCell.h"
  18.  
  19. @interface TableViewController ()
  20.  
  21. @end
  22.  
  23. @implementation TableViewController{
  24.      void (^progressHandler)(NSString *someValue);
  25. }
  26. @synthesize longitude, latitude;
  27.  
  28. -(void)viewWillAppear:(BOOL)animated
  29. {
  30.  
  31.    
  32.     self.navigationController.navigationBar.topItem.title = @"Closest Cup";
  33.     self.title = @"Closest Cup";
  34.     [self.navigationController.navigationBar setTitleTextAttributes:
  35.      [NSDictionary dictionaryWithObjectsAndKeys:
  36.       [UIFont fontWithName:@"Poetsen One" size:29],
  37.       NSFontAttributeName,
  38.       [UIColor whiteColor], NSForegroundColorAttributeName,
  39.       nil]];
  40.    
  41.     //Set background of tableview to "click this button" image
  42.     //_myTableView.backgroundView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"arrowClick2.png"]];
  43.  
  44.    
  45.     //set navbar text color to white and background color to brown-ish
  46.     self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
  47.     self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.18 green:0.16 blue:0.16 alpha:1];
  48.     //make sure no cells are still highlighted when tableview appears
  49.     NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
  50.     [_myTableView deselectRowAtIndexPath:indexPath animated:YES];
  51. }
  52.  
  53. -(void)gestureHandler:(UITapGestureRecognizer*)sender
  54. {
  55.     NSLog(@"works!");
  56. }
  57.  
  58. -(void)loadVenues{
  59.     NSLog(@"Your location - Lat:%@, Long:%@", latitude, longitude);
  60.     //CustomObject *customObject = [[CustomObject alloc]init];
  61.     NSString *base = @"https://api.foursquare.com/v2/venues/explore?client_id=SK34ZCSYWESWVO501VCNPXY5T4ZZPEJSRLVYIBB2OPABNHCY&client_secret=M45XCWUBM23SD00JFTRBKCJSRQLW2VI2CDQ2TEUY0UEKKOGN%20&v=20130815&ll=";
  62.     NSString *coordinatesString = [NSString stringWithFormat:@"%@%@,%@&query=coffee&radius=7000", base,latitude, longitude];
  63.     NSURL *url = [NSURL URLWithString:coordinatesString];
  64.     NSURLRequest *request = [NSURLRequest requestWithURL:url];
  65.    
  66.     AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
  67.     operation.responseSerializer = [AFJSONResponseSerializer serializer];
  68.    
  69.     //Starts progress indicator to show user content is loading
  70.     MBProgressHUD *loading = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
  71.     loading.labelText = @"Finding Coffee";
  72.    
  73.    
  74.  
  75.  
  76.    
  77.    
  78.    
  79.     [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
  80.        
  81.    
  82.         self.venuesDictionary = (NSDictionary *)responseObject;
  83.        
  84.         //Populate arrays with data from responseObject being pulled from foursquare
  85.         _venues = [[[[_venuesDictionary[@"response"]valueForKey:@"groups"]valueForKey:@"items"]valueForKey:@"venue"]valueForKey:@"name"];
  86.        
  87.         _lat = [[[[[_venuesDictionary[@"response"]valueForKey:@"groups"]valueForKey:@"items"]valueForKey:@"venue"]valueForKey:@"location"]valueForKey:@"lat"];
  88.         _lon = [[[[[_venuesDictionary[@"response"]valueForKey:@"groups"]valueForKey:@"items"]valueForKey:@"venue"]valueForKey:@"location"]valueForKey:@"lng"];
  89.         _distance = [[[[[_venuesDictionary[@"response"]valueForKey:@"groups"]valueForKey:@"items"]valueForKey:@"venue"]valueForKey:@"location"]valueForKey:@"distance"];
  90.        
  91.         _prefix = [[[[[[_venuesDictionary[@"response"]valueForKey:@"groups"]valueForKey:@"items"]valueForKey:@"venue"]valueForKey:@"categories"]valueForKey:@"icon"]valueForKey:@"prefix"];
  92.         _address = [[[[[_venuesDictionary[@"response"]valueForKey:@"groups"]valueForKey:@"items"]valueForKey:@"venue"]valueForKey:@"location"]valueForKey:@"address"];
  93.         _city = [[[[[_venuesDictionary[@"response"]valueForKey:@"groups"]valueForKey:@"items"]valueForKey:@"venue"]valueForKey:@"location"]valueForKey:@"city"];
  94.         _state = [[[[[_venuesDictionary[@"response"]valueForKey:@"groups"]valueForKey:@"items"]valueForKey:@"venue"]valueForKey:@"location"]valueForKey:@"state"];
  95.         _zip = [[[[[_venuesDictionary[@"response"]valueForKey:@"groups"]valueForKey:@"items"]valueForKey:@"venue"]valueForKey:@"location"]valueForKey:@"postalCode"];
  96.         _phoneNumber = [[[[[_venuesDictionary[@"response"]valueForKey:@"groups"]valueForKey:@"items"]valueForKey:@"venue"]valueForKey:@"contact"]valueForKey:@"formattedPhone"];
  97.         _website = [[[[_venuesDictionary[@"response"]valueForKey:@"groups"]valueForKey:@"items"]valueForKey:@"venue"]valueForKey:@"url"];
  98.         _rating = [[[[_venuesDictionary[@"response"]valueForKey:@"groups"]valueForKey:@"items"]valueForKey:@"venue"]valueForKey:@"rating"];
  99.         _phone = [[[[[_venuesDictionary[@"response"]valueForKey:@"groups"]valueForKey:@"items"]valueForKey:@"venue"]valueForKey:@"contact"]valueForKey:@"phone"];
  100.        
  101.        
  102.         //NSLog(@"rating: %i",[[_venues objectAtIndex:0] count] );
  103.         //        for (int i = 0; i < [[_website objectAtIndex:0]count]; i++) {
  104.         //            if ([[_website objectAtIndex:0]objectAtIndex:i] != [NSNull null]) {
  105.         //                NSLog(@"not this one");
  106.         //            }else{
  107.         //                NSLog(@"this one's null");
  108.         //            }
  109.         //        }
  110.         //NSLog(@"one: %@", [_prefix objectAtIndex:0]);
  111.         //Address string concatenation
  112.         _addressArray = [[NSMutableArray alloc]init];
  113.         for (int i = 0; i < [_address count]; i++) {
  114.             NSString *address = [[NSString alloc]init];
  115.             address = [NSString stringWithFormat:@"%@\n%@, %@ %@", [_address objectAtIndex:i],[_city objectAtIndex:i],[_state objectAtIndex:i],[_zip objectAtIndex:i]];
  116.             [_addressArray addObject:address];
  117.         }
  118.        
  119.         //miles array and formatter methods
  120.         _miles = [[NSMutableArray alloc]init];
  121.         NSNumber *currentNumber = [[NSNumber alloc]init];
  122.         NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
  123.         [formatter setMaximumFractionDigits:2];
  124.         [formatter setMinimum:0];
  125.         //loops through distance array and converts to miles, only allows 2 decimal places, then puts it in an array
  126.         for (int i = 0; i < [[_distance objectAtIndex:0] count]; i++) {
  127.            
  128.             float currentFloat = [[[_distance objectAtIndex:0]objectAtIndex:i] floatValue] / 1609.34;
  129.             currentNumber = [NSNumber numberWithFloat:currentFloat];
  130.             NSString *formatted = [formatter stringFromNumber:currentNumber];
  131.             [_miles addObject:formatted];
  132.            
  133.         }
  134.        
  135.         //Adds the 88px suffix to all _prefix array strings then adds them to a _paths array
  136.         _paths = [NSMutableArray array];
  137.         //NSLog(@"prefix: %@", [_prefix objectAtIndex:0]);
  138.         //NSLog(@"venues: %@", responseObject);
  139.         for (int i = 0; i < [[_venues objectAtIndex:0] count]; i++) {
  140.            
  141.             if ([[[_prefix objectAtIndex:0]objectAtIndex:i]count] != 0) {
  142.                 NSMutableString *pathStrings = [[NSMutableString alloc]initWithFormat:@"%@88.png", [[[_prefix objectAtIndex:0]objectAtIndex:i] objectAtIndex:0]];
  143.                 [_paths addObject:pathStrings];
  144.             }else if ([[[_prefix objectAtIndex:0]objectAtIndex:i]count] == 0){
  145.                 NSMutableString *pathStrings = [[NSMutableString alloc]initWithString:@""];
  146.                 [_paths addObject:pathStrings];
  147.             }
  148.         }
  149.        
  150.         //creates array of custom objects with venue name and coordinates
  151.         //_objects = [NSMutableArray array];
  152.         _addObjects = [[NSMutableArray alloc]init];
  153.         CustomObject *customObject = [[CustomObject alloc]init];
  154.         for (int i = 0; i < [[_venues objectAtIndex:0]count]; i++) {
  155.            
  156.             if ([[_venues objectAtIndex:0]objectAtIndex:i] != nil) {
  157.                
  158.                
  159.                 NSString *lati = [[_lat objectAtIndex:0]objectAtIndex:i];
  160.                 NSString *longi = [[_lon objectAtIndex:0]objectAtIndex:i];
  161.                 CLLocationCoordinate2D positionCoords = CLLocationCoordinate2DMake([lati doubleValue], [longi doubleValue]);
  162.                
  163.                 [_addObjects addObject:[customObject initWithName:[[_venues objectAtIndex:0]objectAtIndex:i] coordinates:positionCoords website:[[_website objectAtIndex:0]objectAtIndex:i] phone:[[_phoneNumber objectAtIndex:0]objectAtIndex:i] address:[[_address objectAtIndex:0]objectAtIndex:i] rating:[[_rating objectAtIndex:0]objectAtIndex:i] miles:[_miles objectAtIndex:i]]];
  164.                
  165.  
  166.             }
  167.         }
  168. #warning sort
  169.         NSLog(@"%@", _addObjects);
  170. //        [_addObjects sortUsingComparator: ^(id obj1, id obj2) {
  171. //            NSString *dist1 = [obj1 objectAtIndex:1];
  172. //            NSString *dist2 = [obj2 objectAtIndex:1];
  173. //            
  174. //            return [dist1 compare:dist2];
  175. //        }];
  176.        
  177.        
  178.         NSSortDescriptor *sortDescriptor;
  179.         sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"_miles"
  180.                                                      ascending:YES];
  181.         NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
  182.         NSArray *sortedArray = [_addObjects sortedArrayUsingDescriptors:sortDescriptors];
  183.         _objects = [NSMutableArray arrayWithArray:sortedArray];
  184.        
  185.  
  186.        
  187.         //NSLog(@"%@", _objects);
  188.         //NSLog(@"objects: %@", [[_objects objectAtIndex:0]description]);
  189.  
  190.  
  191.         [_myTableView reloadData];
  192.         [MBProgressHUD hideHUDForView:self.view animated:YES];
  193.        
  194.        
  195.     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  196.         UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving venues"
  197.                                                             message:[error localizedDescription]
  198.                                                            delegate:nil
  199.                                                   cancelButtonTitle:@"Ok"
  200.                                                   otherButtonTitles:nil];
  201.         [alertView show];
  202.     }];
  203.     [operation start];
  204. }
  205.  
  206. - (IBAction)getJosephs:(UIBarButtonItem *)sender {
  207.     [self loadVenues];
  208. }
  209.  
  210. - (void)viewDidLoad
  211. {
  212.    
  213.     //This needs to be loaded first before shops are found because the search uses the coordinates to
  214.     locationManager = [[CLLocationManager alloc]init];
  215.     locationManager.delegate = self;
  216.     locationManager.desiredAccuracy = kCLLocationAccuracyBest;
  217.     [locationManager startUpdatingLocation];
  218.    
  219. //#warning don't run loadVenues until location is received
  220.     NSTimer* myTimer = [NSTimer scheduledTimerWithTimeInterval: 1 target: self
  221.                                                       selector: @selector(loadVenues) userInfo: nil repeats: NO];
  222.     //[self loadVenues];
  223.     [super viewDidLoad];
  224.  
  225. }
  226. -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
  227. {
  228.     CLLocation *location = [locations lastObject];
  229.     latitude = [NSString stringWithFormat:@"%f", location.coordinate.latitude];
  230.     longitude = [NSString stringWithFormat:@"%f", location.coordinate.longitude];
  231.  
  232. }
  233.  
  234.  
  235. #pragma mark - Table view data source
  236.  
  237. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  238. {
  239.     // Return the number of sections.
  240.     return 1;
  241. }
  242.  
  243. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  244. {
  245.     // Return the number of rows in the section.
  246.     return [[_venues objectAtIndex:0]count];
  247. }
  248.  
  249. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  250. {
  251.     //NSLog(@"%@", _objects);
  252.  
  253.     VenuesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
  254.  
  255.     CustomObject *currentObject = [_objects objectAtIndex:indexPath.row];
  256.    
  257.     cell.venuesTitle.text = [currentObject nameOfVenue];
  258.     NSString *preDistance = @"about";
  259.     NSString *postDistance = @"miles";
  260.    
  261.    
  262.     cell.venuesSubTitle.text = [NSString stringWithFormat:@"%@ %@ %@", preDistance,[_miles objectAtIndex:indexPath.row] ,postDistance];
  263.    
  264.     if ([[_phoneNumber objectAtIndex:0]objectAtIndex:indexPath.row] != [NSNull null]) {
  265.         cell.phoneIcon.alpha = 1;
  266.     }else{
  267.         cell.phoneIcon.alpha = .4;
  268.     }
  269.    
  270.     if ([[_website objectAtIndex:0]objectAtIndex:indexPath.row] != [NSNull null]) {
  271.         cell.webIcon.alpha = 1;
  272.     }else{
  273.         cell.webIcon.alpha = .4;
  274.     }
  275.    
  276.     if ([[_rating objectAtIndex:0]objectAtIndex:indexPath.row] != [NSNull null]) {
  277.         cell.ratingIcon.alpha = 1;
  278.     }else{
  279.         cell.ratingIcon.alpha = .4;
  280.     }
  281.    
  282.    
  283.    
  284.    
  285.     if (cell != nil) {
  286.         NSMutableString *imagePath = [NSMutableString stringWithFormat:@"%@", [_paths objectAtIndex:indexPath.row]];
  287.         [cell.venuesImage setContentMode:UIViewContentModeScaleAspectFit];
  288.         [cell.venuesImage setImageWithURL:[NSURL URLWithString:imagePath] placeholderImage:[UIImage imageNamed:@"[email protected]"]];
  289.    
  290.     }
  291.     return cell;
  292. }
  293.  
  294. -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  295. {
  296.     DetailCellViewController *DetailCVC = segue.destinationViewController;
  297.    
  298.     UITableViewCell *cell = (UITableViewCell*)sender;
  299.     NSIndexPath *indexPath = [_myTableView indexPathForCell:cell];
  300.     if ([segue.identifier isEqualToString:@"toDetails"]) {
  301.         CustomObject *currentObject = [_objects objectAtIndex:indexPath.row];
  302.         DetailCVC.currentObject = currentObject;
  303.         DetailCVC.phone = [[_phone objectAtIndex:0]objectAtIndex:indexPath.row];
  304.     }
  305.     if ([segue.identifier isEqualToString:@"toAllBusinesses"]) {
  306.         AllBusinessesViewController *AllBusinessesVC = segue.destinationViewController;
  307.         AllBusinessesVC.objects = _objects;
  308.         AllBusinessesVC.latitude = latitude;
  309.         AllBusinessesVC.longitude = longitude;
  310.     }
  311. }
  312.  
  313.  
  314.  
  315. @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement