AppDelegate.m 20 KB

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