Files
eqn.ios/Sources/Earthquake Network/AppDelegate.m
T
2020-07-24 16:21:24 +02:00

348 lines
15 KiB
Objective-C

//
// AppDelegate.m
// Earthquake Network
//
// Created by Luca Beretta on 12/09/18.
// Copyright © 2018 Luca Beretta. All rights reserved.
//
#import "AppDelegate.h"
#import "EQNUser.h"
#import "Costanti.h"
#import "EQMAccelerometroManager.h"
#import "EQNManager.h"
#import "MasterViewController.h"
#import "EQNUtility.h"
#import "EQNAllertaSismica.h"
#import "EQNAllertaSismica.h"
#import "EQNNotificheSegnalazioniUtente.h"
#import "EQNNotificeReteSismiche.h"
@import GoogleMaps;
@import Firebase;
@import UserNotifications;
@import GoogleMobileAds;
@interface AppDelegate () <FIRMessagingDelegate, UNUserNotificationCenterDelegate>
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[GMSServices provideAPIKey:GOOGLE_MAP_KEY];
[GADMobileAds.sharedInstance startWithCompletionHandler:^(GADInitializationStatus *status) {
NSLog(@"[AppDelegate] GADMobileAds started with status: %@", status);
}];
[EQNUser defaultUser];
[EQNManager defaultManager];
[FIRApp configure];
[FIRMessaging messaging].delegate = self;
if ([UNUserNotificationCenter class] != nil) {
// iOS 10 or later
// For iOS 10 display notification (sent via APNS)
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter]
requestAuthorizationWithOptions:authOptions
completionHandler:^(BOOL granted, NSError * _Nullable error) {
// ...
[self registraNotifica];
}];
} else {
// iOS 10 notifications aren't available; fall back to iOS 8-9 notifications.
/* UIUserNotificationType allNotificationTypes =
(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings *settings =
[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
[application registerUserNotificationSettings:settings]; */
[self registraNotifica];
}
[application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
[application registerForRemoteNotifications];
// [[NSUserDefaults standardUserDefaults] setBool:NO forKey:EQN_ACQ_IN_APP];
NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
NSData *receipt = [NSData dataWithContentsOfURL:receiptURL];
if (!receipt) { /* No local receipt -- handle the error. */ }
else{
NSLog(@"ricevuta presente");
}
/* ... Send the receipt data to your server ... */
return YES;
}
-(void)registraNotifica{
UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"notifica_con_mappa" actions:@[] intentIdentifiers:@[] options:UNNotificationCategoryOptionNone];
[[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObject: category]];
}
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
[[EQNManager defaultManager] avviaManager];
[[EQMAccelerometroManager sharedInstance] startUpdatingLocationBackground];
NSUInteger i = [[NSUserDefaults standardUserDefaults] integerForKey:CONTEGGIO_APERTURE_PER_SCONTO];
i++;
if (i == 15)
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:DATA_APERTURE_PER_SCONTO];
[[NSUserDefaults standardUserDefaults] setInteger:i forKey:CONTEGGIO_APERTURE_PER_SCONTO];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
[[EQNManager defaultManager] stopManager];
[[EQMAccelerometroManager sharedInstance] stopUpdatingLocation];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
}
-(void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
}
/////// Gestione Notifiche
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
[[FIRMessaging messaging] appDidReceiveMessage:userInfo];
// Print message ID.
NSLog(@"userInfo %@", userInfo);
if (userInfo[@"type"]) {
NSLog(@"Message ID: %@", userInfo[@"type"]);
}
// Print full message.
NSLog(@"%@", userInfo);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
/*
NSString* jsonString = userInfo[@"gcm.notification.userInfo"];
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments
error:&jsonError];
if ([JSON[@"type"] isEqualToString:@"eqn"]) {
NSDate *dataRicezione = [NSDate date];
[[NSUserDefaults standardUserDefaults] setObject:dataRicezione forKey:NOTIFICHE_RETE_SMARTPHONE_DATA_NOTIFICA];
[EQNUtility writeArrayWithCustomObjToUserDefaults:NOTIFICHE_RETE_SMARTPHONE_DIZIONARIO_NOTIFICA withDict:JSON];
[[NSUserDefaults standardUserDefaults] synchronize];
}
[self.reteSmartphone fetchNewDataWithCompletionHandler:^(UIBackgroundFetchResult result) {
completionHandler(result);
}];*/
completionHandler(UIBackgroundFetchResultNewData);
}
////////////// APPLICAZIONE IN PRIMO PIANO //////////////////////
// Receive displayed notifications for iOS 10 devices.
// Handle incoming notification messages while app is in the foreground.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
NSDictionary *userInfo = notification.request.content.userInfo;
NSIndexPath *indexPath;
if ([userInfo[@"type"] isEqualToString:@"eqn"]) {
NSDate *dataRicezione = [NSDate date];
[[NSUserDefaults standardUserDefaults] setObject:dataRicezione forKey:NOTIFICHE_RETE_SMARTPHONE_DATA_NOTIFICA];
[EQNUtility writeArrayWithCustomObjToUserDefaults:NOTIFICHE_RETE_SMARTPHONE_DIZIONARIO_NOTIFICA withDict:userInfo];
indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[[NSUserDefaults standardUserDefaults] synchronize];
}
else if([userInfo[@"type"] isEqualToString:@"manual"])
indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
else if([userInfo[@"type"] isEqualToString:@"official"])
indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
else if([userInfo[@"type"] isEqualToString:@"tsunami"])
indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
// [self.masterViewController selezionaItem:indexPath];
[self.masterViewController sincronizza];
// Change this to your preferred presentation option
completionHandler(UNNotificationPresentationOptionAlert);
}
////////////// DOPO AVER CLICCATO SULLA NOTIFICA //////////////////////
// Handle notification messages after display notification is tapped by the user.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void(^)(void))completionHandler {
// response.notification.request.content.sound = [UNNotificationSound soundNamed:[EQNAllertaSismica center].tonoAllarme];
NSDictionary *userInfo = response.notification.request.content.userInfo;
NSIndexPath *indexPath;
if ([userInfo[@"type"] isEqualToString:@"eqn"]) {
NSDate *dataRicezione = [NSDate date];
[[NSUserDefaults standardUserDefaults] setObject:dataRicezione forKey:NOTIFICHE_RETE_SMARTPHONE_DATA_NOTIFICA];
[EQNUtility writeArrayWithCustomObjToUserDefaults:NOTIFICHE_RETE_SMARTPHONE_DIZIONARIO_NOTIFICA withDict:userInfo];
indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[[NSUserDefaults standardUserDefaults] synchronize];
}
else if([userInfo[@"type"] isEqualToString:@"manual"])
indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
else if([userInfo[@"type"] isEqualToString:@"official"])
indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
else if([userInfo[@"type"] isEqualToString:@"tsunami"])
indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
[self.masterViewController sincronizza];
[self.masterViewController selezionaItem:indexPath];
// Print full message.
completionHandler();
}
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
[self.masterViewController fetchNewDataWithCompletionHandler:^(UIBackgroundFetchResult result) {
completionHandler(result);
}];
}
#pragma mark - Core Data stack
@synthesize persistentContainer = _persistentContainer;
- (NSPersistentContainer *)persistentContainer {
// The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
@synchronized (self) {
if (_persistentContainer == nil) {
_persistentContainer = [[NSPersistentContainer alloc] initWithName:@"Earthquake_Network"];
[_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
if (error != nil) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
NSLog(@"Unresolved error %@, %@", error, error.userInfo);
abort();
}
}];
}
}
return _persistentContainer;
}
#pragma mark - Core Data Saving support
- (void)saveContext {
NSManagedObjectContext *context = self.persistentContainer.viewContext;
NSError *error = nil;
if ([context hasChanges] && ![context save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, error.userInfo);
abort();
}
}
- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {
// Notify about received token.
// NSDictionary *dataDict = [NSDictionary dictionaryWithObject:fcmToken forKey:@"token"];
// [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICA_TOKEN object:nil userInfo:dataDict];
NSLog(@"fcmToken %@", fcmToken);
if (![[NSUserDefaults standardUserDefaults] objectForKey:TOKEN_USER]) {
[EQNAllertaSismica center].isAbilitato = YES;
[EQNAllertaSismica center].raggioSismiLievi = @"300";
[EQNAllertaSismica center].raggioSismiForti = @"600";
[EQNAllertaSismica center].sismiDaNotificare = @"0";
[EQNAllertaSismica center].isSimiSenzaIntensita = YES;;
[[EQNAllertaSismica center] saveUserInfo];
[EQNNotificheSegnalazioniUtente center].isAbilitato = YES;
[EQNNotificheSegnalazioniUtente center].distanzaPosizione = @"300";
[[EQNNotificheSegnalazioniUtente center] saveUserInfo];
[EQNNotificeReteSismiche center].isAbilitato = YES;
[EQNNotificeReteSismiche center].distanzaPosizione = @"1000";
[EQNNotificeReteSismiche center].distanzaVicini = @"100";
[EQNNotificeReteSismiche center].isAbilitaVicini = NO;
[EQNNotificeReteSismiche center].energiaSisma = @"3.5";
[EQNNotificeReteSismiche center].energiaTerremotiForti = @"7.5";
[[EQNNotificeReteSismiche center] saveUserInfo];
}
[[NSUserDefaults standardUserDefaults] setObject:fcmToken forKey:TOKEN_USER];
[EQNUser defaultUser].tokenUser = fcmToken;
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}
@end