AppDelegate.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. //
  2. // AppDelegate.m
  3. // Apex And Drivers
  4. //
  5. // Created by Ray on 2018/5/26.
  6. // Copyright © 2018 USAI. All rights reserved.
  7. //
  8. #import "AppDelegate.h"
  9. #import <UserNotifications/UserNotifications.h>
  10. #import "LoginViewController.h"
  11. #import "RAHomeViewController.h"
  12. #import <CoreLocation/CoreLocation.h>
  13. #import "RANavigationController.h"
  14. #import "RAExceptionHandler.h"
  15. @interface AppDelegate ()<UNUserNotificationCenterDelegate,CLLocationManagerDelegate>
  16. @property (nonatomic,strong) CLLocationManager *locationManager;
  17. @property (nonatomic,strong) NSDictionary *currentOrderNotification;
  18. @end
  19. @implementation AppDelegate
  20. #pragma mark - Private
  21. - (void)showHomeVC{
  22. RAHomeViewController *homeVC = [RAHomeViewController viewControllerFromStoryboard];
  23. RANavigationController *nav = [[RANavigationController alloc] initWithRootViewController:homeVC];
  24. self.window.rootViewController = nav;
  25. }
  26. - (void)showLoginVC {
  27. LoginViewController *rootVC = [LoginViewController viewControllerFromStoryboard];
  28. __weak typeof(self) weakSelf = self;
  29. rootVC.loginSuccessful = ^(NSString *user,NSString *password){
  30. [[RASingleton sharedInstance] loginUser:user password:password];
  31. [weakSelf showHomeVC];
  32. };
  33. UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:rootVC];
  34. self.window.rootViewController = nav;
  35. }
  36. - (void)saveUploadTasks {
  37. if(self.uploadManager.arr_queue!=nil)
  38. {
  39. [self.uploadManager stopAllTasks];
  40. [self.uploadManager saveTasks];
  41. }
  42. }
  43. - (void)startLocation {
  44. if (self.locationManager) {
  45. return;
  46. }
  47. self.locationManager = [[CLLocationManager alloc] init];
  48. self.locationManager.delegate = self;
  49. self.locationManager.allowsBackgroundLocationUpdates = YES;
  50. self.locationManager.pausesLocationUpdatesAutomatically = NO; // 是否允许系统自动暂停定位
  51. self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;//设置定位精度
  52. self.locationManager.distanceFilter = 10; //不需要移动都可以刷新,不然不移动就不会执行定位,不定位的话,那么后台进程也就挂起了
  53. [self.locationManager requestAlwaysAuthorization];
  54. [self.locationManager startUpdatingLocation];
  55. }
  56. - (void)stopLocation {
  57. if (self.locationManager == nil) {
  58. return;
  59. }
  60. [self.locationManager stopUpdatingLocation];
  61. self.locationManager = nil;
  62. }
  63. - (void)receiveLogoutNotification:(NSNotification *)notification {
  64. [self showLoginVC];
  65. }
  66. - (void)receiveStartLocationNotification:(NSNotification *)notification {
  67. [self startLocation];
  68. }
  69. - (void)receiveStopLocationNotification:(NSNotification *)notification {
  70. [self stopLocation];
  71. }
  72. - (void)registActionNotification {
  73. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveLogoutNotification:) name:RANotificationLogout object:nil];
  74. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveStartLocationNotification:) name:RANotificationStartLocation object:nil];
  75. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveStopLocationNotification:) name:RANotificationStopLocation object:nil];
  76. }
  77. #pragma mark - AppDelegate
  78. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  79. // Override point for customization after application launch.
  80. // NSString *orderID = nil;
  81. // NSInteger orderType = OrderTypeNew;
  82. // NSString *orderType2 = nil;
  83. // if (launchOptions) {
  84. // NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
  85. // NSDictionary *aps = [userInfo objectForKey:@"aps"];
  86. // orderID = [aps objectForKey:@"order-id"];
  87. // orderType = [[aps objectForKey:@"order-type"] integerValue];
  88. // orderType2 = [aps objectForKey:@"order-type2"];
  89. //
  90. // }
  91. [RAExceptionHandler registHandler:^(NSString *exceptionStr) {
  92. NSLog(@"Exception:\n%@",exceptionStr);
  93. }];
  94. // View
  95. self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  96. self.window.backgroundColor = [UIColor whiteColor];
  97. if (RASingleton.sharedInstance.autoLogin) {
  98. [self showHomeVC];
  99. } else {
  100. [self showLoginVC];
  101. }
  102. [self.window makeKeyAndVisible];
  103. [RASingleton.sharedInstance loadSavedReuqiredLocation];
  104. //
  105. [self registActionNotification];
  106. //消息推送注册
  107. UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter];
  108. [center setDelegate:self];
  109. UNAuthorizationOptions type = UNAuthorizationOptionBadge|UNAuthorizationOptionSound|UNAuthorizationOptionAlert;
  110. [center requestAuthorizationWithOptions:type completionHandler:^(BOOL granted, NSError * _Nullable error) {
  111. if (granted) {
  112. NSLog(@"推送通知授权成功");
  113. }else{
  114. NSLog(@"推送通知授权失败");
  115. }
  116. }];
  117. [application registerForRemoteNotifications];
  118. // 程序被强杀之后收到通知,点击 通知 启动应用
  119. if (launchOptions && application.applicationState == UIApplicationStateInactive) {
  120. NSMutableDictionary *userInfo = [[launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey] mutableCopy];
  121. if (userInfo) {
  122. [userInfo setObject:@(YES) forKey:@"go2Detail"];
  123. [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationHandleOrder object:nil userInfo:userInfo];
  124. }
  125. }
  126. // [RASingleton.sharedInstance writeLog:[NSString stringWithFormat:@"isActive: %ld %s launchOptions:%@",application.applicationState,__func__,launchOptions]];
  127. return YES;
  128. }
  129. - (void)applicationDidBecomeActive:(UIApplication *)application {
  130. if (!self.uploadManager) {
  131. self.uploadManager=[[RAUploadManager alloc] init];
  132. }
  133. [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
  134. // 程序在后台收到通知后,直接打开程序的情况下弹窗提示
  135. if (self.currentOrderNotification) {
  136. [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationHandleOrder object:nil userInfo:self.currentOrderNotification];
  137. self.currentOrderNotification = nil;
  138. }
  139. }
  140. - (void)applicationWillTerminate:(UIApplication *)application {
  141. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  142. [self saveUploadTasks];
  143. }
  144. - (void)dealloc {
  145. [[NSNotificationCenter defaultCenter] removeObserver:self];
  146. }
  147. #pragma mark - Notification
  148. //完成注册后收到devicetoken
  149. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  150. //上传deviceToken给后台服务器
  151. NSString *fullStr = [deviceToken description];
  152. NSLog(@"fullstr= %@",fullStr);
  153. NSString *deviceTokenStr = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
  154. NSLog(@"deviceTokenStr:\n%@",deviceTokenStr);
  155. [[RASingleton sharedInstance] setNotificationToken:deviceTokenStr];
  156. }
  157. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  158. NSLog(@"注册推送失败:%@",error);
  159. }
  160. //处理通知
  161. - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
  162. // 程序在前台收到通知
  163. UNNotificationRequest *request = notification.request;
  164. NSDictionary *userInfo = request.content.userInfo;
  165. if ([request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
  166. NSLog(@"收到远程通知: %@",userInfo);
  167. } else {
  168. NSLog(@"收到本地通知: %@",userInfo);
  169. }
  170. // UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert
  171. completionHandler(UNNotificationPresentationOptionNone);
  172. }
  173. - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
  174. NSLog(@"接收到推送内容==%@", response.notification.request.content.userInfo);
  175. // 点击通知
  176. // NSDictionary *userInfo = response.notification.request.content.userInfo;
  177. // if (userInfo) {
  178. //
  179. // NSDictionary *aps = [userInfo objectForKey:@"aps"];
  180. //
  181. // NSInteger is_order = [[aps objectForKey:@"is-order"] integerValue];
  182. // if (is_order) {
  183. // [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationHandleOrder object:nil userInfo:userInfo];
  184. // }
  185. // }
  186. // [RASingleton.sharedInstance writeLog:[NSString stringWithFormat:@"isActive: %ld %s",[UIApplication sharedApplication].applicationState,__func__]];
  187. self.currentOrderNotification = nil;
  188. NSMutableDictionary *userInfo = [response.notification.request.content.userInfo mutableCopy];
  189. [userInfo setObject:@(YES) forKey:@"go2Detail"];
  190. [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationHandleOrder object:nil userInfo:userInfo];
  191. completionHandler();
  192. }
  193. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  194. // [RASingleton.sharedInstance writeLog:[NSString stringWithFormat:@"isActive: %ld %s",application.applicationState,__func__]];
  195. /**
  196. 静默推送alert为空
  197. {
  198. "aps" : {
  199. "alert" : "",
  200. "content-available" : 1
  201. }
  202. }
  203. */
  204. // "content-available" : 1 收到通知
  205. NSLog(@"收到静默推送: %@",userInfo);
  206. if (userInfo) {
  207. NSDictionary *aps = [userInfo objectForKey:@"aps"];
  208. NSInteger report_location = [[aps objectForKey:@"report-location"] integerValue];
  209. if (report_location == 1) {
  210. NSString *orderID = [aps objectForKey:@"order-id"];
  211. if (RASingleton.sharedInstance.backgroundReportType == RABackgroundReportTypeAllow) {
  212. [self reportLocation:[RASingleton sharedInstance].currentLocation forOrder:orderID];
  213. } else if (RASingleton.sharedInstance.backgroundReportType == RABackgroundReportTypeAlways) {
  214. [self reportLocationWithOrder:orderID];
  215. } else if (RASingleton.sharedInstance.backgroundReportType == RABackgroundReportTypeReject) {
  216. [self rejectReportLocationWithReason:[NSString stringWithFormat:@"Driver %@ rejected to report location",RASingleton.sharedInstance.user] forOrder:orderID];
  217. }
  218. completionHandler(UIBackgroundFetchResultNewData);
  219. } else {
  220. /**
  221. {
  222. "aps" : {
  223. "alert" : {
  224. "title" : "Notification",
  225. "body" : "You have a new order"
  226. },
  227. "is-order" : 1,
  228. "order-id" : "AFS20180530001200",
  229. "order-type2" : "Pick Up",
  230. "order-type" : 2,
  231. "sound" : "default",
  232. "content-available" : 1
  233. }
  234. }
  235. */
  236. NSInteger is_order = [[aps objectForKey:@"is-order"] integerValue];
  237. if (is_order) {
  238. // 程序在前台,弹窗提示
  239. if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
  240. [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationHandleOrder object:nil userInfo:userInfo];
  241. } else {
  242. // 程序在后台,记录下来。当程序重新进入前台时弹窗提示(没有点击通知打开程序的情况)
  243. self.currentOrderNotification = userInfo;
  244. }
  245. }
  246. completionHandler(UIBackgroundFetchResultNewData);
  247. }
  248. } else {
  249. completionHandler(UIBackgroundFetchResultNoData);
  250. }
  251. }
  252. #pragma mark - Local Notification
  253. - (void)sendLocalNotification:(NSString *)title message:(NSString *)msg {
  254. // 创建Content
  255. UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
  256. content.title = title;
  257. content.body = msg;
  258. content.badge = @([UIApplication sharedApplication].applicationIconBadgeNumber + 1);
  259. // 创建Request,保证ID一致
  260. UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"local_notification" content:content trigger:nil];
  261. // 发送
  262. [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
  263. if (!error) {
  264. NSLog(@"发送本地通知:%@",request.identifier);
  265. }
  266. }];
  267. }
  268. #pragma mark - Report Location
  269. - (void)rejectReportLocationWithReason:(NSString *)reason forOrder:(NSString *)orderID {
  270. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  271. [RADataProvider reportLocationWithUserReason:reason forOrder:orderID];
  272. });
  273. }
  274. - (void)reportLocation:(CLLocation *)location forOrder:(NSString *)orderID {
  275. if (location) {
  276. NSString *latLon = [NSString stringWithFormat:@"%f,%f",location.coordinate.latitude,location.coordinate.longitude];
  277. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  278. [RADataProvider reportCurrentLocation:latLon forOrderID:orderID];
  279. });
  280. } else {
  281. }
  282. }
  283. - (void)reportLocationWithOrder:(NSString *)orderID {
  284. UIViewController *topVC = self.window.rootViewController;
  285. while (topVC.presentedViewController) {
  286. topVC = topVC.presentedViewController;
  287. }
  288. if (topVC) {
  289. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"Warning" message:[NSString stringWithFormat:@"Report Location For Order:%@",orderID] preferredStyle:UIAlertControllerStyleAlert];
  290. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  291. [self rejectReportLocationWithReason:[NSString stringWithFormat:@"Driver %@ cancel to report location",RASingleton.sharedInstance.user] forOrder:orderID];
  292. }];
  293. __weak typeof(self) weakSelf = self;
  294. UIAlertAction *reportAction = [UIAlertAction actionWithTitle:@"Report" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
  295. [weakSelf reportLocation:[RASingleton sharedInstance].currentLocation forOrder:orderID];
  296. }];
  297. [alertVC addAction:cancelAction];
  298. [alertVC addAction:reportAction];
  299. [topVC presentViewController:alertVC animated:YES completion:nil];
  300. [self sendLocalNotification:@"Report Location Notification" message:[NSString stringWithFormat:@"The Apex ask your location for order:%@",orderID]];
  301. }
  302. }
  303. #pragma mark - LocationManager Delegate
  304. - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
  305. if (locations.count) {
  306. [RASingleton sharedInstance].currentLocation = [locations lastObject];
  307. NSLog(@"location: %f, %f",[RASingleton sharedInstance].currentLocation.coordinate.latitude,[RASingleton sharedInstance].currentLocation.coordinate.longitude);
  308. // 省电,停止不能超过三分钟
  309. // [self performSelector:@selector(stopLocation) withObject:nil afterDelay:10]; // 获取到位置10s后关闭位置服务
  310. // [self performSelector:@selector(startLocation) withObject:nil afterDelay:120]; // 获取到位置120s后重新打开位置服务
  311. CLLocationDistance distance = 500;
  312. NSTimeInterval time = 60;
  313. [manager allowDeferredLocationUpdatesUntilTraveled:distance timeout:time];
  314. }
  315. }
  316. - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
  317. if (status == kCLAuthorizationStatusDenied) {
  318. [RASingleton sharedInstance].currentLocation = nil;
  319. }
  320. }
  321. @end