// // GraphViewController.m // Volta // // Created by Ronny Fenrich on 2013-06-17. // Copyright (c) 2013 Decoder. All rights reserved. // #import "GraphViewController.h" #import "StatsTabBarController.h" #import "VoltaReading.h" @interface GraphViewController () @property (weak, nonatomic) IBOutlet UIWebView *webView; @end @implementation GraphViewController - (void)viewDidLoad { [super viewDidLoad]; NSString *resourcePath = [[[[NSBundle mainBundle] resourcePath] stringByReplacingOccurrencesOfString:@"/" withString:@"//"] stringByReplacingOccurrencesOfString:@" " withString:@"%20"]; NSString *markup = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"graph" ofType:@"html"] encoding:NSUTF8StringEncoding error:nil]; dispatch_async(dispatch_get_main_queue(), ^{ [self.webView loadHTMLString:markup baseURL:[NSURL URLWithString:[NSString stringWithFormat:@"file:/%@//", resourcePath]]]; }); } - (void)viewDidUnload { [self setWebView:nil]; [super viewDidUnload]; } - (void)viewWillDisappear { if (self.webView.loading) { [self.webView stopLoading]; } } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [self hideGradientBackground:self.webView]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"MMM dd"]; NSString *seriesA = @""; NSString *seriesB = @""; StatsTabBarController *parentTabBarController = (StatsTabBarController *)self.parentViewController; for (VoltaReading *reading in parentTabBarController.data.allValues) { float kWh = reading.usage / 1000.0f; float cost = reading.cost / 100000.0f; if (![seriesA isEmpty]) { seriesA = [seriesA stringByAppendingString:@","]; } if (![seriesB isEmpty]) { seriesB = [seriesB stringByAppendingString:@","]; } seriesA = [seriesA stringByAppendingString:[NSString stringWithFormat:@"['%@', %.2f]", [dateFormatter stringFromDate:reading.startDate], kWh]]; seriesB = [seriesB stringByAppendingString:[NSString stringWithFormat:@"['%@', %.2f]", [dateFormatter stringFromDate:reading.startDate], cost]]; } seriesA = [[@"[" stringByAppendingString:seriesA] stringByAppendingString:@"]"]; seriesB = [[@"[" stringByAppendingString:seriesB] stringByAppendingString:@"]"]; double delayInSeconds = 0.5; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"plotData(%@, %@)", seriesA, seriesB]]; }); } #pragma mark - Web View - (void)hideGradientBackground:(UIView*)theView { for (UIView * subview in theView.subviews) { if ([subview isKindOfClass:[UIImageView class]]) subview.hidden = YES; [self hideGradientBackground:subview]; } } - (void)webView:(UIWebView *)theWebView didFailLoadWithError:(NSError *)error { // If the URLLoadingSystem cancelled the load don't show anything. NSString *errorUrl = [error.userInfo objectForKey:@"NSErrorFailingURLStringKey"]; if (([error code] != NSURLErrorCancelled ) && ([[errorUrl uppercaseString] startsWith:@"HTTP"])) { BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Connection Error" message:@"We couldn't load the web page, please check your internet connection and try again."]; [alert setCancelButtonWithTitle:@"Ok" block:nil]; [alert show]; } } - (BOOL)webView:(UIWebView *)theWebView shouldStartLoadWithRequest:(NSURLRequest *)theRequest navigationType:(UIWebViewNavigationType)navigationType { // if ([[theRequest.URL absoluteString] isEqual:@"flushd://ready"]) // { // // pass in statistic data when webview is ready... // NSError *jsonError = nil; // NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self.statsController.userStats // options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string // error:&jsonError]; // if (jsonError) // { // BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Error" message:@"Couldn't process statistic data. Please try again later."]; // [alert setCancelButtonWithTitle:@"Ok" block:nil]; // [alert show]; // [self.spinner stopAnimating]; // [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; // } // else // { // NSString *jsonStatsData = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; // NSLog(@"%@", jsonStatsData); // // // save world rank for later... // id usersWorldRankValue = [self.statsController.userStats valueForKeyPath:@"week.global_rank"]; // if (usersWorldRankValue && !([usersWorldRankValue isEqual:[NSNull null]])) { // self.usersWorldRank = [usersWorldRankValue integerValue]; // } // // // dispatch_async(dispatch_get_main_queue(), ^{ // [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"recalculateStats(%@)", jsonStatsData]]; // }); // } // return NO; // } // else // // webview is updated => present to the user now // if ([[theRequest.URL absoluteString] isEqual:@"flushd://loaded"]) // { // // slide in webview from bottom of screen now // int finalWebViewPosition = self.webView.$y; // self.webView.$y = [[UIScreen mainScreen] applicationFrame].size.height + 20; // self.webView.hidden = NO; // self.shareButton.hidden = NO; // // [UIView animateWithDuration:0.4 // delay:0.6 // options:UIViewAnimationOptionCurveEaseOut // animations:^{ // // self.webView.$y = finalWebViewPosition; // // } completion:^(BOOL finished) { // // [self.spinner stopAnimating]; // [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; // self.webView.$y = finalWebViewPosition; // // // new badges? trigger javascript to show alert to the user // UIViewController *pController = self.parentViewController; // if ([pController isKindOfClass:[FlushdCustomTabBarController class]] && [pController respondsToSelector:@selector(setStatsBadge:)]) // { // FlushdCustomTabBarController *aFlushdTabBarController = (FlushdCustomTabBarController *)pController; // if (aFlushdTabBarController.badgeLabel.tag > 0) { // dispatch_async(dispatch_get_main_queue(), ^{ // [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"showNewAchievementsPopup(%i)", aFlushdTabBarController.badgeLabel.tag]]; // }); // // // remove badges after user is looking at the stats page... // [self removeStatsBadge]; // } // } // }]; // return NO; // } // return YES; } - (void)webViewDidFinishLoad:(UIWebView *)theWebView { // scroll to the top [self.webView.scrollView setContentOffset:CGPointMake(0, 0)]; } - (void)webViewDidStartLoad:(UIWebView *)theWebView { } @end