Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 487 lines (399 sloc) 18.423 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
//
// CRSReportViewController.m
// RealTimeCongress
//
// Created by Tom Tsai on 8/10/11.
// Copyright 2011 Sunlight Labs. All rights reserved.
//

#import "CRSReportViewController.h"
#import "WhipNoticesWebViewController.h"
#import "SunlightLabsRequest.h"
#import "JSONKit.h"
#import "GANTracker.h"
#import "Reachability.h"

#pragma mark Utility extensions

@interface UILabel (sizingExtensions)
- (void)sizeToFitFixedWidth:(NSInteger)fixedWidth;
@end

@implementation UILabel (sizingExtensions)


- (void)sizeToFitFixedWidth:(NSInteger)fixedWidth
{
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, fixedWidth, 0);
    self.lineBreakMode = UILineBreakModeWordWrap;
    self.numberOfLines = 0;
    [self sizeToFit];
}
@end

@implementation CRSReportViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    [super dealloc];
    [sectionDataArray release];
    [reachabilityInfo release];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //Set title
    self.title = @"CRS Reports";

    //Set up refresh button
    UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh)];
    self.navigationItem.rightBarButtonItem = refreshButton;
    [refreshButton release];
    
    //Register for reachability changed notifications
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged)
                                                 name:kReachabilityChangedNotification
                                               object:nil];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [reachabilityInfo stopNotifier];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // Check if URL Cache memory size is set to zero. Reset to 10 MB if it is.
    if([[NSURLCache sharedURLCache] memoryCapacity] == 0){
        [[NSURLCache sharedURLCache] setMemoryCapacity:10485760];
    }
    
    //Array to keep track of the unique days for each update
    if (!reportDaysArray){
        reportDaysArray = [[NSMutableArray alloc] initWithCapacity:20];
    }
    
    // Create a dictionary to associate updates with days
    reportDaysDictionary = [[NSMutableDictionary dictionary] retain];
    
    //Create a reachability object to monitor internet reachability
    reachabilityInfo = [[Reachability reachabilityForInternetConnection] retain];
    [reachabilityInfo startNotifier];
    
    //Retrieve data
    [self retrieveData];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    
    //iPad supports all orientations
    if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
        return YES;
    }
    else {
        //iPhone supports only portrait orientation
        return (interfaceOrientation == UIInterfaceOrientationPortrait);
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    if ([reportDaysArray count] > 0) {
        return ([reportDaysArray count] + 1);
    }
    else{
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (section == 0) {
        return 1;
    }
    else {
        NSArray *sectionArray = [sectionDataArray objectAtIndex:section - 1];
        return [sectionArray count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *TopCell = @"TopCell";
    static NSString *TableCell = @"TableCell";
    
    
    // Set informative text in the top most cell
    if (indexPath.section == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TopCell];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TopCell] autorelease];
        }
        [cell.textLabel sizeToFitFixedWidth:CELL_WIDTH];
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.text = @"Reports issued by the Congressional Research Service, an arm of the Library of Congress that provides Congress with research and analysis on legislative issues.";
        cell.userInteractionEnabled = NO;
        return cell;
    }
    
    else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableCell];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:TableCell] autorelease];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        
        NSArray *sectionArray = [sectionDataArray objectAtIndex:(indexPath.section - 1)];
        
        if (sectionArray != NULL) {
            // Configure the cell...
            [cell.textLabel sizeToFitFixedWidth:CELL_WIDTH];
            cell.textLabel.text = [[sectionArray objectAtIndex:indexPath.row] objectForKey:@"title"];
        }
        return cell;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    // Sets the title of each section to the legislative day
    if ([reportDaysArray count] > 0) {
        if ((section == [reportDaysArray count]) || (section == 0)) {
            return nil;
        }
        else {
            return [reportDaysArray objectAtIndex:section - 1];
        }
        
    }
    else {
        return [NSString stringWithString:@"No events logged"];
    }
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    WhipNoticesWebViewController *webViewController = [[WhipNoticesWebViewController alloc] initWithNibName:@"WhipNoticesWebViewController" bundle:nil];
    NSArray *sectionArray = [sectionDataArray objectAtIndex:(indexPath.section - 1)];
    NSURL * url = [NSURL URLWithString:[[sectionArray objectAtIndex:indexPath.row] objectForKey:@"url"]];
    NSURLRequest * urlRequest = [NSURLRequest requestWithURL:url];
    webViewController.urlRequest = urlRequest;
    webViewController.launchType = @"crs_reports";
    [self.navigationController pushViewController:webViewController animated:YES];
    [webViewController release];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 90;
    }
    else {
        //Calculates the appropriate row height based on the size of the three text labels
        CGSize maxSize = CGSizeMake(CELL_WIDTH, CGFLOAT_MAX);
        NSArray *sectionArray = [sectionDataArray objectAtIndex:(indexPath.section - 1)];
        
        CGSize titleTextSize = [[[sectionArray objectAtIndex:indexPath.row] objectForKey:@"title"] sizeWithFont:[UIFont boldSystemFontOfSize:17] constrainedToSize:maxSize];
        
        return (titleTextSize.height + 60);
    }
}

#pragma mark - UI Actions

- (void) refresh
{
    // Check network reachability. If unreachable, display alert view. Otherwise, retrieve data
    NetworkStatus internetStatus = [reachabilityInfo currentReachabilityStatus];
    if (internetStatus != NotReachable) {
        //Disable scrolling while data is loading
        self.tableView.scrollEnabled = NO;
  
        NSError *error;
        //Register a page view to the Google Analytics tracker
        if (![[GANTracker sharedTracker] trackPageview:@"/crs_reports"
                                             withError:&error]) {
            // Handle error here
        }
        
        // Generate request URL using Sunlight Labs Request class
        NSDictionary *requestParameters = [[NSDictionary alloc] initWithObjectsAndKeys:
                                           [NSString stringWithFormat:@"%@", REQUEST_PAGE_SIZE], @"per_page",
                                           @"crs_report", @"document_type",
                                           nil];
        SunlightLabsRequest *dataRequest = [[SunlightLabsRequest alloc] initRequestWithParameterDictionary:requestParameters APICollection:Documents APIMethod:nil];
        connection = [[SunlightLabsConnection alloc] initWithSunlightLabsRequest:dataRequest];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(parseData:) name:SunglightLabsRequestFinishedNotification object:connection];
        [connection sendRequest];
        
        [dataRequest release];
        [requestParameters release];
    }
    else {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"The internet is currently inaccessible."
                                                         message:@"Please check your connection and try again."
                                                        delegate:self
                                               cancelButtonTitle:@"Ok"
                                               otherButtonTitles:nil];
        
        [alert show];
        [alert release];
    }
}

- (void) parseData: (NSNotification *)notification
{
    //Release connection upon data receiption
    [connection release];
    connection = nil;
    
    // Clear array when new data received
    [reportDaysArray removeAllObjects];
    
    // Clear dictionary of updates when new data received
    [reportDaysDictionary removeAllObjects];
    
    //Assign received data
    NSDictionary *items = [notification userInfo];
    
    static NSDateFormatter * dateFormatter;
    static NSDateFormatter *updateDayFormatter;
    
    if (dateFormatter == nil) {
        dateFormatter = [[NSDateFormatter alloc] init];
    }
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    
    if (updateDayFormatter == nil) {
        updateDayFormatter = [[NSDateFormatter alloc] init];
    }
    [updateDayFormatter setDateFormat:@"EEEE, MMMM dd"];
    
    for (id update in [items objectForKey:@"documents"]) {
        NSDate * date = [dateFormatter dateFromString:[update objectForKey:@"released_at"]];
        
        // Check if the date has been added to update days array. Add it if it hasn't.
        NSString *updateDay = [updateDayFormatter stringFromDate: date];
        if (![reportDaysArray containsObject: updateDay]) {
            [reportDaysArray addObject:updateDay];
        }
        
        // Check if there is an array for the update day. If there isn't, create an array to store updates for that day.
        if ([reportDaysDictionary objectForKey:updateDay] == nil) {
            [reportDaysDictionary setObject:[NSMutableArray array] forKey:updateDay];
            // Add the update to its respective array
            [[reportDaysDictionary objectForKey:updateDay] addObject:update];
        }
        else {
            // Add the update to its respective array if it already exists
            [[reportDaysDictionary objectForKey:updateDay] addObject:update];
        }
    }
    
    sectionDataArray = [[NSMutableArray alloc] initWithCapacity:20];
    
    for (NSString *updateDayString in reportDaysArray) {
        if (updateDayString != @"") {
            [sectionDataArray addObject:[reportDaysDictionary objectForKey:updateDayString]];
        }
    }
    
    //Reload the table once data retrieval is complete
    [self.tableView reloadData];

    //Re-enable scrolling once loading is complete and the loading indicator disappears
    self.tableView.scrollEnabled = YES;
}

- (void) parseCachedData:(NSData *)data {
    NSDictionary *items = [[JSONDecoder decoder] objectWithData:data];
    
    static NSDateFormatter * dateFormatter;
    static NSDateFormatter *updateDayFormatter;
    
    if (dateFormatter == nil) {
        dateFormatter = [[NSDateFormatter alloc] init];
    }
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    
    if (updateDayFormatter == nil) {
        updateDayFormatter = [[NSDateFormatter alloc] init];
    }
    [updateDayFormatter setDateFormat:@"EEEE, MMMM dd"];
    
    for (id update in [items objectForKey:@"documents"]) {
        NSDate * date = [dateFormatter dateFromString:[update objectForKey:@"released_at"]];
        
        // Check if the date has been added to update days array. Add it if it hasn't.
        NSString *updateDay = [updateDayFormatter stringFromDate: date];
        if (![reportDaysArray containsObject: updateDay]) {
            [reportDaysArray addObject:updateDay];
        }
        
        // Check if there is an array for the update day. If there isn't, create an array to store updates for that day.
        if ([reportDaysDictionary objectForKey:updateDay] == nil) {
            [reportDaysDictionary setObject:[NSMutableArray array] forKey:updateDay];
            // Add the update to its respective array
            [[reportDaysDictionary objectForKey:updateDay] addObject:update];
        }
        else {
            // Add the update to its respective array if it already exists
            [[reportDaysDictionary objectForKey:updateDay] addObject:update];
        }
    }
    
    sectionDataArray = [[NSMutableArray alloc] initWithCapacity:20];
    
    for (NSString *updateDayString in reportDaysArray) {
        [sectionDataArray addObject:[reportDaysDictionary objectForKey:updateDayString]];
    }
    
    //Reload the table once data retrieval is complete
    [self.tableView reloadData];
     
    //Re-enable scrolling once loading is complete and the loading indicator disappears
    self.tableView.scrollEnabled = YES;
}

- (void) retrieveData
{
    NSError *error;
    //Register a page view to the Google Analytics tracker
    if (![[GANTracker sharedTracker] trackPageview:@"/crs_reports"
                                         withError:&error]) {
        // Handle error here
    }
    
    // Generate request URL using Sunlight Labs Request class
    NSDictionary *requestParameters = [[NSDictionary alloc] initWithObjectsAndKeys:
                                       [NSString stringWithFormat:@"%@", REQUEST_PAGE_SIZE], @"per_page",
                                       @"crs_report", @"document_type",
                                       nil];
    SunlightLabsRequest *dataRequest = [[SunlightLabsRequest alloc] initRequestWithParameterDictionary:requestParameters APICollection:Documents APIMethod:nil];
    
    NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:[dataRequest request]];
    NSDate *responseAge = [[cachedResponse userInfo] objectForKey:@"CreationDate"];
    NSDate *currentDate = [NSDate date];
   
    // Check if there is an unexpired cached response
    if ((cachedResponse != nil) && ([currentDate timeIntervalSinceDate:responseAge] < 300)) {
        [self parseCachedData:[[[NSURLCache sharedURLCache] cachedResponseForRequest:[dataRequest request]] data]];
    }
    else{
        // Check network reachability. If unreachable, display alert view. Otherwise, retrieve data
        NetworkStatus internetStatus = [reachabilityInfo currentReachabilityStatus];
        if (internetStatus != NotReachable) {
            connection = [[SunlightLabsConnection alloc] initWithSunlightLabsRequest:dataRequest];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(parseData:) name:SunglightLabsRequestFinishedNotification object:connection];
            [connection sendRequest];
        }
        else {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"The internet is currently inaccessible."
                                                             message:@"Please check your connection and try again."
                                                            delegate:self
                                                   cancelButtonTitle:@"Ok"
                                                   otherButtonTitles:nil];
            
            [alert show];
            [alert release];
        }
    }
    
    [dataRequest release];
    [requestParameters release];
}

- (void) reachabilityChanged {
    NetworkStatus internetStatus = [reachabilityInfo currentReachabilityStatus];
    if (internetStatus == NotReachable) {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"The internet is currently inaccessible."
                                                         message:@"Please check your connection and try again."
                                                        delegate:self
                                               cancelButtonTitle:@"Ok"
                                               otherButtonTitles:nil];
        
        [alert show];
        [alert release];
        
    }
    else {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Internet now accessible."
                                                         message:@"Internet now accessible."
                                                        delegate:self
                                               cancelButtonTitle:@"Ok"
                                               otherButtonTitles:nil];
        
        [alert show];
        [alert release];
    }
}


@end
Something went wrong with that request. Please try again.