| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427 |
- //
- // AppDelegate.m
- // Apex And Drivers
- //
- // Created by Ray on 2018/5/26.
- // Copyright © 2018 USAI. All rights reserved.
- //
- #import "AppDelegate.h"
- #import <UserNotifications/UserNotifications.h>
- #import "LoginViewController.h"
- #import "RAHomeViewController.h"
- #import <CoreLocation/CoreLocation.h>
- #import "RANavigationController.h"
- #import "RAExceptionHandler.h"
- @interface AppDelegate ()<UNUserNotificationCenterDelegate,CLLocationManagerDelegate>
- @property (nonatomic,strong) CLLocationManager *locationManager;
- @property (nonatomic,strong) NSDictionary *currentOrderNotification;
- @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"];
- //
- // }
-
- [RAExceptionHandler registHandler:^(NSString *exceptionStr) {
-
- NSLog(@"Exception:\n%@",exceptionStr);
-
- }];
-
-
- // 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];
-
-
-
- // 程序被强杀之后收到通知,点击 通知 启动应用
- if (launchOptions && application.applicationState == UIApplicationStateInactive) {
-
- NSMutableDictionary *userInfo = [[launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey] mutableCopy];
- if (userInfo) {
- [userInfo setObject:@(YES) forKey:@"go2Detail"];
- [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationHandleOrder object:nil userInfo:userInfo];
- }
- }
-
- // [RASingleton.sharedInstance writeLog:[NSString stringWithFormat:@"isActive: %ld %s launchOptions:%@",application.applicationState,__func__,launchOptions]];
- return YES;
- }
- - (void)applicationDidBecomeActive:(UIApplication *)application {
-
- if (!self.uploadManager) {
- self.uploadManager=[[RAUploadManager alloc] init];
- }
- [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
-
- // 程序在后台收到通知后,直接打开程序的情况下弹窗提示
- if (self.currentOrderNotification) {
- [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationHandleOrder object:nil userInfo:self.currentOrderNotification];
- self.currentOrderNotification = nil;
- }
- }
- - (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];
- // }
- // }
- // [RASingleton.sharedInstance writeLog:[NSString stringWithFormat:@"isActive: %ld %s",[UIApplication sharedApplication].applicationState,__func__]];
-
- self.currentOrderNotification = nil;
-
- NSMutableDictionary *userInfo = [response.notification.request.content.userInfo mutableCopy];
- [userInfo setObject:@(YES) forKey:@"go2Detail"];
- [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationHandleOrder object:nil userInfo:userInfo];
-
- completionHandler();
- }
- - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
- // [RASingleton.sharedInstance writeLog:[NSString stringWithFormat:@"isActive: %ld %s",application.applicationState,__func__]];
- /**
- 静默推送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];
- } else if (RASingleton.sharedInstance.backgroundReportType == RABackgroundReportTypeReject) {
-
- [self rejectReportLocationWithReason:[NSString stringWithFormat:@"Driver %@ rejected to report location",RASingleton.sharedInstance.user] forOrder: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) {
-
- // 程序在前台,弹窗提示
- if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
-
- [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationHandleOrder object:nil userInfo:userInfo];
-
- } else {
- // 程序在后台,记录下来。当程序重新进入前台时弹窗提示(没有点击通知打开程序的情况)
- self.currentOrderNotification = 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)rejectReportLocationWithReason:(NSString *)reason forOrder:(NSString *)orderID {
- dispatch_async(dispatch_get_global_queue(0, 0), ^{
- [RADataProvider reportLocationWithUserReason:reason forOrder:orderID];
- });
- }
- - (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) {
-
- [self rejectReportLocationWithReason:[NSString stringWithFormat:@"Driver %@ cancel to report location",RASingleton.sharedInstance.user] forOrder:orderID];
-
- }];
-
- __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<CLLocation *> *)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
|