// // AppDelegate.m // Apex And Drivers // // Created by Ray on 2018/5/26. // Copyright © 2018 USAI. All rights reserved. // #import "AppDelegate.h" #import #import "LoginViewController.h" #import "RAHomeViewController.h" #import #import "RANavigationController.h" static const NSInteger OrderTypeNew = 2; @interface AppDelegate () @property (nonatomic,strong) CLLocationManager *locationManager; @end @implementation AppDelegate #pragma mark - Private - (void)showHomeVC{ RAHomeViewController *homeVC = [RAHomeViewController viewControllerFromStoryboard]; RANavigationController *nav = [[RANavigationController alloc] initWithRootViewController:homeVC]; self.window.rootViewController = nav; } - (void)showLoginVC { LoginViewController *rootVC = [LoginViewController viewControllerFromStoryboard]; __weak typeof(self) weakSelf = self; rootVC.loginSuccessful = ^(NSString *user,NSString *password){ [[RASingleton sharedInstance] loginUser:user password:password]; [weakSelf showHomeVC]; }; UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:rootVC]; self.window.rootViewController = nav; } - (void)saveUploadTasks { if(self.uploadManager.arr_queue!=nil) { [self.uploadManager stopAllTasks]; [self.uploadManager saveTasks]; } } - (void)startLocation { if (self.locationManager) { return; } self.locationManager = [[CLLocationManager alloc] init]; self.locationManager.delegate = self; self.locationManager.allowsBackgroundLocationUpdates = YES; self.locationManager.pausesLocationUpdatesAutomatically = NO; // 是否允许系统自动暂停定位 self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;//设置定位精度 self.locationManager.distanceFilter = 10; //不需要移动都可以刷新,不然不移动就不会执行定位,不定位的话,那么后台进程也就挂起了 [self.locationManager requestAlwaysAuthorization]; [self.locationManager startUpdatingLocation]; } - (void)stopLocation { if (self.locationManager == nil) { return; } [self.locationManager stopUpdatingLocation]; self.locationManager = nil; } - (void)receiveLogoutNotification:(NSNotification *)notification { [self showLoginVC]; } - (void)receiveStartLocationNotification:(NSNotification *)notification { [self startLocation]; } - (void)receiveStopLocationNotification:(NSNotification *)notification { [self stopLocation]; } - (void)registActionNotification { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveLogoutNotification:) name:RANotificationLogout object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveStartLocationNotification:) name:RANotificationStartLocation object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveStopLocationNotification:) name:RANotificationStopLocation object:nil]; } #pragma mark - AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. // NSString *orderID = nil; // NSInteger orderType = OrderTypeNew; // NSString *orderType2 = nil; // if (launchOptions) { // NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]; // NSDictionary *aps = [userInfo objectForKey:@"aps"]; // orderID = [aps objectForKey:@"order-id"]; // orderType = [[aps objectForKey:@"order-type"] integerValue]; // orderType2 = [aps objectForKey:@"order-type2"]; // // } // View self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds]; self.window.backgroundColor = [UIColor whiteColor]; if (RASingleton.sharedInstance.autoLogin) { [self showHomeVC]; } else { [self showLoginVC]; } [self.window makeKeyAndVisible]; [RASingleton.sharedInstance loadSavedReuqiredLocation]; // [self registActionNotification]; //消息推送注册 UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter]; [center setDelegate:self]; UNAuthorizationOptions type = UNAuthorizationOptionBadge|UNAuthorizationOptionSound|UNAuthorizationOptionAlert; [center requestAuthorizationWithOptions:type completionHandler:^(BOOL granted, NSError * _Nullable error) { if (granted) { NSLog(@"推送通知授权成功"); }else{ NSLog(@"推送通知授权失败"); } }]; [application registerForRemoteNotifications]; return YES; } - (void)applicationDidBecomeActive:(UIApplication *)application { if (!self.uploadManager) { self.uploadManager=[[RAUploadManager alloc] init]; } [UIApplication sharedApplication].applicationIconBadgeNumber = 0; } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. [self saveUploadTasks]; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } #pragma mark - Notification //完成注册后收到devicetoken - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { //上传deviceToken给后台服务器 NSString *fullStr = [deviceToken description]; NSLog(@"fullstr= %@",fullStr); NSString *deviceTokenStr = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""]; NSLog(@"deviceTokenStr:\n%@",deviceTokenStr); [[RASingleton sharedInstance] setNotificationToken:deviceTokenStr]; } - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { NSLog(@"注册推送失败:%@",error); } //处理通知 - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { // 程序在前台收到通知 UNNotificationRequest *request = notification.request; NSDictionary *userInfo = request.content.userInfo; if ([request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) { NSLog(@"收到远程通知: %@",userInfo); } else { NSLog(@"收到本地通知: %@",userInfo); } // UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert completionHandler(UNNotificationPresentationOptionNone); } - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler { NSLog(@"接收到推送内容==%@", response.notification.request.content.userInfo); // 点击通知 // NSDictionary *userInfo = response.notification.request.content.userInfo; // if (userInfo) { // // NSDictionary *aps = [userInfo objectForKey:@"aps"]; // // NSInteger is_order = [[aps objectForKey:@"is-order"] integerValue]; // if (is_order) { // [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationHandleOrder object:nil userInfo:userInfo]; // } // } completionHandler(); } /** 程序处于非运行状态时,收到通知,点击Icon运行程序会调用此方法 程序处于运行状态或后台,收到通知也会调用此方法。 */ - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { /** 静默推送alert为空 { "aps" : { "alert" : "", "content-available" : 1 } } */ // "content-available" : 1 收到通知 NSLog(@"收到静默推送: %@",userInfo); if (userInfo) { NSDictionary *aps = [userInfo objectForKey:@"aps"]; NSInteger report_location = [[aps objectForKey:@"report-location"] integerValue]; if (report_location == 1) { NSString *orderID = [aps objectForKey:@"order-id"]; if (RASingleton.sharedInstance.backgroundReportType == RABackgroundReportTypeAllow) { [self reportLocation:[RASingleton sharedInstance].currentLocation forOrder:orderID]; } else if (RASingleton.sharedInstance.backgroundReportType == RABackgroundReportTypeAlways) { [self reportLocationWithOrder:orderID]; } completionHandler(UIBackgroundFetchResultNewData); } else { /** { "aps" : { "alert" : { "title" : "Notification", "body" : "You have a new order" }, "is-order" : 1, "order-id" : "AFS20180530001200", "order-type2" : "Pick Up", "order-type" : 2, "sound" : "default", "content-available" : 1 } } */ NSInteger is_order = [[aps objectForKey:@"is-order"] integerValue]; if (is_order) { [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationHandleOrder object:nil userInfo:userInfo]; } completionHandler(UIBackgroundFetchResultNewData); } } else { completionHandler(UIBackgroundFetchResultNoData); } } #pragma mark - Local Notification - (void)sendLocalNotification:(NSString *)title message:(NSString *)msg { // 创建Content UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]; content.title = title; content.body = msg; content.badge = @([UIApplication sharedApplication].applicationIconBadgeNumber + 1); // 创建Request,保证ID一致 UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"local_notification" content:content trigger:nil]; // 发送 [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (!error) { NSLog(@"发送本地通知:%@",request.identifier); } }]; } #pragma mark - Report Location - (void)reportLocation:(CLLocation *)location forOrder:(NSString *)orderID { if (location) { NSString *latLon = [NSString stringWithFormat:@"%f,%f",location.coordinate.latitude,location.coordinate.longitude]; dispatch_async(dispatch_get_global_queue(0, 0), ^{ [RADataProvider reportCurrentLocation:latLon forOrderID:orderID]; }); } else { } } - (void)reportLocationWithOrder:(NSString *)orderID { UIViewController *topVC = self.window.rootViewController; while (topVC.presentedViewController) { topVC = topVC.presentedViewController; } if (topVC) { UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"Warning" message:[NSString stringWithFormat:@"Report Location For Order:%@",orderID] preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { }]; __weak typeof(self) weakSelf = self; UIAlertAction *reportAction = [UIAlertAction actionWithTitle:@"Report" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) { [weakSelf reportLocation:[RASingleton sharedInstance].currentLocation forOrder:orderID]; }]; [alertVC addAction:cancelAction]; [alertVC addAction:reportAction]; [topVC presentViewController:alertVC animated:YES completion:nil]; [self sendLocalNotification:@"Report Location Notification" message:[NSString stringWithFormat:@"The Apex ask your location for order:%@",orderID]]; } } #pragma mark - LocationManager Delegate - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { if (locations.count) { [RASingleton sharedInstance].currentLocation = [locations lastObject]; NSLog(@"location: %f, %f",[RASingleton sharedInstance].currentLocation.coordinate.latitude,[RASingleton sharedInstance].currentLocation.coordinate.longitude); // 省电,停止不能超过三分钟 // [self performSelector:@selector(stopLocation) withObject:nil afterDelay:10]; // 获取到位置10s后关闭位置服务 // [self performSelector:@selector(startLocation) withObject:nil afterDelay:120]; // 获取到位置120s后重新打开位置服务 CLLocationDistance distance = 500; NSTimeInterval time = 60; [manager allowDeferredLocationUpdatesUntilTraveled:distance timeout:time]; } } - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { if (status == kCLAuthorizationStatusDenied) { [RASingleton sharedInstance].currentLocation = nil; } } @end