// // AllerteViewController.m // Earthquake Network // // Refactored by Andrea Busi on 04/10/2020 // Copyright © 2020 Earthquake Network. All rights reserved. // #import "AllerteViewController.h" #import "Costanti.h" #import "ServerRequest.h" #import "EQNGeneratoreURLServer.h" #import "EQNManager.h" #import "EQNUser.h" #import "EQNAreaCheck.h" @import StoreKit; @import SafariServices; @import CoreLocation; @interface AllerteViewController () @property (weak, nonatomic) IBOutlet UIBarButtonItem *expandeCollapseButton; @property (weak, nonatomic) IBOutlet UITableView *tableView; @property (strong, nonatomic) NSMutableArray *tableItems; @property (nonatomic) BOOL isNotificaAttiva; @end @implementation AllerteViewController static NSString * const SegueIdentifierPrioritySubscriptions = @"ShowPrioritySubscriptions"; /// Sections inside the app typedef NS_ENUM(NSInteger, AllerteTableRow) { AllerteTableRowLocationPermission = 0, AllerteTableRowSismiRilevati, AllerteTableRowAllertePassate, AllerteTableRowReteSmartphone, AllerteTableRowServizioPriorita, AllerteTableRowDatiPosizione }; #pragma mark - Accessories - (NSMutableArray *)tableItems { if (!_tableItems) { _tableItems = [[NSMutableArray alloc] init]; } return _tableItems; } #pragma mark - View Lifecycle - (void)viewDidLoad { [super viewDidLoad]; [self setupUI]; [self refreshUI]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForegroundNotification:) name:UIApplicationWillEnterForegroundNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangeAuthorizationStatusNotification:) name:EQNAuthorizationStatusDidChangeNotification object:nil]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self refreshUI]; } #pragma mark - Notification - (void)applicationWillEnterForegroundNotification:(NSNotification *)notification { [self refreshUI]; } - (void)didChangeAuthorizationStatusNotification:(NSNotification *)notification { [self refreshUI]; } #pragma mark - Public - (void)fetchNewDataWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { dispatch_async(dispatch_get_main_queue(), ^{ [self refreshUI]; }); completionHandler(UIBackgroundFetchResultNewData); } #pragma mark - Private - (void)setupUI { self.title = [NSLocalizedString(@"tab_network", nil) capitalizedString]; self.tableView.estimatedRowHeight = 600.0; self.tableView.rowHeight = UITableViewAutomaticDimension; } - (void)refreshUI { [super refreshUI]; // `AllerteTableRowReteSmartphone` and `AllerteTableRowDatiPosizione` are hidden bu default, user can show them BOOL showAllCards = AppPreferences.shared.alertsShowAllCards; self.expandeCollapseButton.image = showAllCards ? [UIImage imageNamed:@"navbar-icon-arrow-collapse"] : [UIImage imageNamed:@"navbar-icon-arrow-expand"]; // controlliamo se c'è una notifica in tempo reale da mostrare NSDate *date = [[NSUserDefaults standardUserDefaults] objectForKey:EQNUserDefaultRealTimeAlertDate]; NSDictionary *info = [EQNUtility loadDictionaryFromUserDefaultsForKey:EQNUserDefaultRealTimeAlertPayload]; if (date && info && [EQNUtility getDifferenceMinute:date] < EQNRealtimeAlertExpiration) { self.isNotificaAttiva = YES; // mostriamo la schermata solo se il countdown non è a zero EQNRealtimeAlert *alert = [[EQNRealtimeAlert alloc] initWithNotification:info]; if (alert != nil && ![alert isCountdownExpired]) { RealtimeAlertViewController *controller = [[RealtimeAlertViewController alloc] initWithAlert:alert]; if (@available(iOS 13.0, *)) { controller.modalInPresentation = YES; } [self presentViewController:controller animated:YES completion:nil]; } } else { [self resetRealtimeAlert]; } [self.tableItems removeAllObjects]; // rows always visible [self.tableItems addObjectsFromArray:@[ @(AllerteTableRowSismiRilevati), @(AllerteTableRowAllertePassate), @(AllerteTableRowServizioPriorita)]]; if (showAllCards) { [self.tableItems addObject:@(AllerteTableRowReteSmartphone)]; } // check if locations is enabled if (CLLocationManager.authorizationStatus != kCLAuthorizationStatusAuthorizedAlways) { [self.tableItems addObject:@(AllerteTableRowLocationPermission)]; } // location data visible only if last position is known if ([EQNUser defaultUser].lastPosition != nil && showAllCards) { [self.tableItems addObject:@(AllerteTableRowDatiPosizione)]; } // sort items based on enum position NSSortDescriptor *sorter = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES]; [self.tableItems sortUsingDescriptors:@[sorter]]; [self.tableView reloadData]; } - (void)resetRealtimeAlert { [[NSUserDefaults standardUserDefaults] removeObjectForKey:EQNUserDefaultRealTimeAlertDate]; [[NSUserDefaults standardUserDefaults] removeObjectForKey:EQNUserDefaultRealTimeAlertPayload]; self.isNotificaAttiva = NO; } #pragma mark - Actions - (IBAction)refreshDataTapped:(id)sender { [[EQNManager defaultManager] sincronizza]; } - (IBAction)collapseExpandTapped:(id)sender { // toggle saved value AppPreferences.shared.alertsShowAllCards = !AppPreferences.shared.alertsShowAllCards; [self refreshUI]; } - (void)actionCloseNotification { [self resetRealtimeAlert]; [self.tableView reloadData]; } - (void)actionShareApp { NSString *content = NSLocalizedString(@"main_share_text", @""); UIActivityViewController* activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[content] applicationActivities:nil]; [self presentViewController:activityViewController animated:YES completion:nil]; } - (void)actionRateApp { [SKStoreReviewController requestReview]; } - (void)actionOpenTwitter { NSURL *twitterUrl = [NSURL URLWithString:EQNTwitterProfileUrl]; SFSafariViewController *controller = [[SFSafariViewController alloc] initWithURL:twitterUrl]; [self presentViewController:controller animated:YES completion:nil]; } - (void)actionOpenSimulator { AlertSimulatorViewController *controller = [[AlertSimulatorViewController alloc] init]; [self presentViewController:controller animated:YES completion:nil]; } - (void)actionHowItWorks { NSURL *youtubeUrl = [NSURL URLWithString:NSLocalizedString(@"youtube_video", nil)]; SFSafariViewController *controller = [[SFSafariViewController alloc] initWithURL:youtubeUrl]; [self presentViewController:controller animated:YES completion:nil]; } - (void)actionTestPush { CLAuthorizationStatus status = CLLocationManager.authorizationStatus; if (status != kCLAuthorizationStatusAuthorizedAlways && status != kCLAuthorizationStatusAuthorizedWhenInUse) { UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"attention", nil) message:NSLocalizedString(@"liveview_unknown_location", nil) preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"ok", nil) style:UIAlertActionStyleCancel handler:nil]]; [self presentViewController:alert animated:YES completion:nil]; return; } NSURL *url = [EQNGeneratoreURLServer urlAlertPushTest]; [[ServerRequest defaultServerConnectionSingleton] inviaInformazioniAlServerWithURL:url richiesta:EQNTipoChiamataAlertPushTest success:^(id result) { // nope } failure:^(NSError *error) { dispatch_async(dispatch_get_main_queue(), ^{ UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"attention", @"") message:error.localizedDescription preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"ok", nil) style:UIAlertActionStyleCancel handler:nil]]; [self presentViewController:alert animated:YES completion:nil]; }); }]; } #pragma table view - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.tableItems.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { AllerteTableRow tableRow = [self.tableItems[indexPath.row] integerValue]; if (tableRow == AllerteTableRowLocationPermission) { AlertsNoLocationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NoLocationCell" forIndexPath:indexPath]; cell.status = CLLocationManager.authorizationStatus; return cell; } else if (tableRow == AllerteTableRowSismiRilevati) { if (self.isNotificaAttiva) { AlertsSeismicNotificationExpandedTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SeismicNotificationExpandedCell" forIndexPath:indexPath]; NSDictionary *info = [EQNUtility loadDictionaryFromUserDefaultsForKey:EQNUserDefaultRealTimeAlertPayload]; cell.notification = info; __weak AllerteViewController *weakSelf = self; cell.onTapClose = ^{ [weakSelf actionCloseNotification]; }; cell.onTapShareApp = ^{ [weakSelf actionShareApp]; }; cell.onTapRateApp = ^{ [weakSelf actionRateApp]; }; cell.onTapOpenTwitter = ^{ [weakSelf actionOpenTwitter]; }; return cell; } AlertsSeismicNotificationCompactTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SeismicNotificationCell" forIndexPath:indexPath]; __weak AllerteViewController *weakSelf = self; cell.onTapAlertTest = ^{ [weakSelf actionTestPush]; }; cell.onTapSimulator = ^{ [weakSelf actionOpenSimulator]; }; cell.onTapHowItWorks = ^{ [weakSelf actionHowItWorks]; }; cell.onTapShareApp = ^{ [weakSelf actionShareApp]; }; return cell; } else if (tableRow == AllerteTableRowAllertePassate) { AlertsPastEartquakesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PastEarthquakesCell" forIndexPath:indexPath]; cell.smartphoneNetwork = [EQNManager defaultManager].rete_smartphone; cell.onTapMapButton = ^{ PasquakesMapViewController *controller = [[PasquakesMapViewController alloc] init]; [self presentViewController:controller animated:YES completion:nil]; }; return cell; } else if (tableRow == AllerteTableRowReteSmartphone) { AlertsSmartphoneNetworkTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SmartphoneNetworkCell" forIndexPath:indexPath]; cell.smartphoneNetwork = [EQNManager defaultManager].rete_smartphone; cell.onTapButton = ^{ [self visualizzaCopertura]; }; return cell; } else if (tableRow == AllerteTableRowServizioPriorita) { AlertsPriorityServiceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PriorityCell" forIndexPath:indexPath]; cell.smartphoneNetwork = [EQNManager defaultManager].rete_smartphone; return cell; } else if (tableRow == AllerteTableRowDatiPosizione) { AlertsPositionDataTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PositionDataCell" forIndexPath:indexPath]; cell.position = [EQNUser defaultUser].lastPosition; return cell; } return nil; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:YES]; AllerteTableRow tableRow = [self.tableItems[indexPath.row] integerValue]; switch (tableRow) { case AllerteTableRowServizioPriorita: [self performSegueWithIdentifier:SegueIdentifierPrioritySubscriptions sender:nil]; break; default: break; } } - (void)visualizzaCopertura { [[EQNManager defaultManager] sincronizza]; EQNAreaCheck *areaCheck = [EQNManager defaultManager].area_check; NSString *message = [NSString stringWithFormat:NSLocalizedString(@"main_areacheck_message", @""), areaCheck.total]; UIAlertController * alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"main_coverage" , @"") message:message preferredStyle:UIAlertControllerStyleAlert]; [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"ok" ,@"") style:UIAlertActionStyleDefault handler:nil]]; [self presentViewController:alertController animated:YES completion:nil]; } @end