AppDelegate.m 15 KB

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