Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

8. Local Search PacktLocal > Time for action — consuming the foursquare venue A...

Time for action — consuming the foursquare venue API - categories

Time for action — consuming the foursquare venue API - categories Open Xcode, and start a new project named Hello foursquare, using the Tabbed Application template.Add a new header file (.h extension) to your project, by selecting the File | New | New File | C and C++ option from Xcode file menu. Name the new file as Configuration.h. This file will hold the foursquare client ID and client secret, and any other foursquare configuration that we might need in future. Keep the configuration in one place, make the code more robust and easy-to-extend, as anyone can start using the code by replacing the configuration values. You can define the values in the Configuration.h file as follows: #ifndef Hello_foursquare_Configuration_h #define Hello_foursquare_Configuration_h #define CLIENT_ID @"XXXXXXXXXXXXXXXX" #define CLIENT_SECRET @"YYYYYYYYYYYYYYYY" #endif Here, XXXX is your client ID, and YYYY is your client secret.Next, add the Core Location, MapKit, Twitter, and SQLite framework to your project. This is similar to our previous projects and examples. We will discuss more on how these libraries are used, as we learn more over the course of this chapter. Rewind back to Chapter 6, Events App - PacktEvents, for a quick look at some of these topics, notably JSON parsing, Twitter, and SQLite.In the Hello_foursquareFirstViewController.h and Hello_foursquareFirstViewController.m files, implement the Core Location delegate and the Core Location manager's methods. We also use the region monitoring through CLRegions for San Francisco, Mumbai, and New York. CLLocationCoordinate2D regionCords = CLLocationCoordinate2DMake(37.33 , -122.03); CLRegion *sanFranciscoBoundary = [[CLRegion alloc] initCircularRegionWithCenter:regionCords radius:5000 identifier:@"San Francisco"]; regionCords = CLLocationCoordinate2DMake(40.71490, -74.00679); CLRegion *newYorkBoundary = [[CLRegion alloc] initCircularRegionWithCenter:regionCords radius:5000 identifier:@"New York"]; regionCords = CLLocationCoordinate2DMake(19.142472, 72.841198); CLRegion *mumbaiBoundary = [[CLRegion alloc] initCircularRegionWithCenter:regionCords radius:5000 identifier:@"Mumbai"]; [locationManager startUpdatingLocation]; [locationManager startMonitoringForRegion:sanFranciscoBoundary]; [locationManager startMonitoringForRegion:newYorkBoundary]; [locationManager startMonitoringForRegion:mumbaiBoundary]; After we are done with the location handling code, we call the initializeDatabase method that is used to create our initial tables. For now, we create the categories table using the following table structure: CREATE TABLE IF NOT EXISTS 'categories' ('id' VARCHAR PRIMARY KEY NOT NULL , 'name' VARCHAR, 'type' VARCHAR, 'categoryid' VARCHAR, 'subCategoryId' VARCHAR, 'icon' VARCHAR) To get an idea on how we are going to store the category hierarchy, please see the following screenshot, where we depict the response from the foursquare category API, and our local SQLite database storage for the first few category values: After we are done with the database initialization, we call the getfoursquareCategories method that does a NSURLConnection call to the foursquare API, for retrieving categories information, as follows: NSString *url = [NSString stringWithFormat:@"https://api.foursquare.com/v2 /venues/categories?&client_id=%@&client_secret=%@", CLIENT_ID,CLIENT_SECRET]; Here CLIENT_IDand CLIENT_SECRET are values that we defined in Configuration.h.Once the connection finishes loading the data through the connectionDidFinishLoading method, we parse the received JSON, and retrieve the category information by converting the JSON data first to an NSDictionary, and thereafter from an NSDictionary to NSArray, for easier parsing. We then generate our INSERT statements, and populate the SQLite database with the category information. Note that we also receive the category icon from foursquare, which we have inserted in our table. - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSError *jsonError; NSDictionary *dictionary; NSArray *items; dictionary= [NSJSONSerialization JSONObjectWithData:jsonContent options:NSJSONReadingAllowFragments error:&jsonError]; if([dictionary count]>0) { items = [NSArray arrayWithObject:[[dictionary objectForKey:@"response"]objectForKey:@"categories"]]; NSUInteger count = [[items objectAtIndex:0]count]; for(NSInteger i=0;i<count;i++) { NSString *categoryId = [[[items objectAtIndex:0] objectAtIndex:i]objectForKey:@"id"]; NSString *categoryName = [[[items objectAtIndex:0] objectAtIndex:i]objectForKey:@"name"]; NSString *categoryIcon = [[[items objectAtIndex:0] objectAtIndex:i]objectForKey:@"icon"]; NSString *categoryType = @"category"; NSString *subCategories = [[[items objectAtIndex:0] objectAtIndex:i]objectForKey:@"categories"]; NSString *icon = [[[items objectAtIndex:0] objectAtIndex:i]objectForKey:@"icon"]; NSString *insertStatement = [[NSString alloc] initWithFormat: @"INSERT OR REPLACE INTO '%@'('%@','%@','%@','%@','%@') VALUES('%@',\"%@\",\"%@\",'%@','%@')",categoriesTableName,@"id",@"name",@"type",@"categoryid",@"icon",categoryId,categoryName,categoryType,categoryId,icon]; if(sqlite3_open([sqliteFileName UTF8String], &database)==SQLITE_OK) { if(sqlite3_exec(database, [insertStatement UTF8String],NULL, NULL, &sqliteError)==SQLITE_OK) { NSLog(@"category table populated"); } else { NSLog(@"%s",sqliteError); } } } // end of for loop [self showCategoriesFromLocal]; } } Most categories in the foursquare category hierarchy also have more subcategories within them, for example the Airport category has the following sub categories: airport food court, airport gates, airport lounges, airport terminals, and so on. Feel free to use them as your application demands. For now, we have captured the same in the subCategories variable.We now define one more method that reads the values from the locally stored categories table. We name this function as showCategoriesFromLocal. A simple select statement is executed here, which retrieves the category info from the local SQLite database, and adds it to an NSArray variable that is used to render on a UITableView. - (void)showCategoriesFromLocal { categories = [[NSMutableArray alloc]init]; if(sqlite3_open([sqliteFileName UTF8String], &database)==SQLITE_OK) { NSString *selectStatement =[[NSString alloc]initWithFormat: @"SELECT * from %@",categoriesTableName]; sqlite3_stmt *sqlStatement; if(sqlite3_prepare_v2(database, [selectStatement UTF8String], -1, &sqlStatement, NULL)==SQLITE_OK) { while(sqlite3_step(sqlStatement)==SQLITE_ROW) { NSString *titleDataText=[NSString stringWithUTF8String: (char *)sqlite3_column_text(sqlStatement, 1)]; if(![categories containsObject:titleDataText]) { [categories addObject:titleDataText]; } } } }// end of if of sqlite3 open [myTableView reloadData]; } Make sure you that use the right variable name in the cellForRowAtIndexPath delegate method of the UITableView. In this case, the categories variable is as follows: NSString *cellContent=[categories objectAtIndex:indexPath.row]; Running the application should produce the following result. Note we leave the UI design to the reader; we use storyboard here, which will be discussed in more detail in Chapter 9, Location Aware News - PacktNews. You could choose to use the default Tabbed Application template, without selecting the Use Storyboard checkbox option. Note that storyboarding only helps in easier user interface management. So, if you think you can handle the UI without storyboard, you can choose to not select it. What just happened? We consumed the foursquare venue category API using the JSON parsing API in iOS5, and created a local table for storing the category information. foursquare recommends purging the category information after a week. But, for most apps, this is highly unlikely, since the app is built around some of these popular categories. But, depending upon your requirement, use the API and caching wisely. We used the storyboard for our app, for which we will have a full-length explanation coming in the next chapters. We also used a separate configuration file to keep the foursquare API keys and Auth configuration values separate from the core app. A similar approach could be used for region monitoring using CLRegion and custom map annotations in separate files, to make the code flow better organized.

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint