AppDelegate.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 = 10;
  172. }];
  173. self.uploadManager=[[RAUploadManager alloc] init];
  174. }
  175. [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
  176. // 程序在后台收到通知后,直接打开程序的情况下弹窗提示
  177. if (self.currentOrderNotification) {
  178. [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationHandleOrder object:nil userInfo:self.currentOrderNotification];
  179. self.currentOrderNotification = nil;
  180. }
  181. }
  182. - (void)applicationWillTerminate:(UIApplication *)application {
  183. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  184. [self saveUploadTasks];
  185. }
  186. - (void)dealloc {
  187. [[NSNotificationCenter defaultCenter] removeObserver:self];
  188. }
  189. #pragma mark - Notification
  190. //完成注册后收到devicetoken
  191. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  192. //上传deviceToken给后台服务器
  193. NSString *fullStr = [deviceToken description];
  194. NSLog(@"fullstr= %@",fullStr);
  195. NSString *deviceTokenStr = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
  196. NSLog(@"deviceTokenStr:\n%@",deviceTokenStr);
  197. [[RASingleton sharedInstance] setNotificationToken:deviceTokenStr];
  198. }
  199. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  200. NSLog(@"注册推送失败:%@",error);
  201. }
  202. //处理通知
  203. - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
  204. // 程序在前台收到通知
  205. UNNotificationRequest *request = notification.request;
  206. NSDictionary *userInfo = request.content.userInfo;
  207. if ([request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
  208. NSLog(@"收到远程通知: %@",userInfo);
  209. } else {
  210. NSLog(@"收到本地通知: %@",userInfo);
  211. }
  212. // UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert
  213. completionHandler(UNNotificationPresentationOptionNone);
  214. }
  215. - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
  216. NSLog(@"接收到推送内容==%@", response.notification.request.content.userInfo);
  217. // 点击通知
  218. // NSDictionary *userInfo = response.notification.request.content.userInfo;
  219. // if (userInfo) {
  220. //
  221. // NSDictionary *aps = [userInfo objectForKey:@"aps"];
  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. // }
  228. // [RASingleton.sharedInstance writeLog:[NSString stringWithFormat:@"isActive: %ld %s",[UIApplication sharedApplication].applicationState,__func__]];
  229. self.currentOrderNotification = nil;
  230. NSMutableDictionary *userInfo = [response.notification.request.content.userInfo mutableCopy];
  231. [userInfo setObject:@(YES) forKey:@"go2Detail"];
  232. [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationHandleOrder object:nil userInfo:userInfo];
  233. completionHandler();
  234. }
  235. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  236. // [RASingleton.sharedInstance writeLog:[NSString stringWithFormat:@"isActive: %ld %s",application.applicationState,__func__]];
  237. /**
  238. 静默推送alert为空
  239. {
  240. "aps" : {
  241. "alert" : "",
  242. "content-available" : 1
  243. }
  244. }
  245. */
  246. // "content-available" : 1 收到通知
  247. NSLog(@"收到静默推送: %@",userInfo);
  248. if (userInfo) {
  249. NSDictionary *aps = [userInfo objectForKey:@"aps"];
  250. NSInteger report_location = [[aps objectForKey:@"report-location"] integerValue];
  251. if (report_location == 1) {
  252. NSString *orderID = [aps objectForKey:@"order-id"];
  253. BOOL tracing = [[aps objectForKey:@"tracing"] boolValue];
  254. NSString *locationId = [aps objectForKey:@"location-id"];
  255. if (tracing) {
  256. if (RASingleton.sharedInstance.backgroundReportType == RABackgroundReportTypeAllow) {
  257. [self reportLastLocation:[RASingleton sharedInstance].lastLocation forOrder:orderID locationID:locationId];
  258. } else {
  259. [self rejectReportLocationWithReason:[NSString stringWithFormat:@"Driver %@ rejected to report location",RASingleton.sharedInstance.user] forOrder:orderID locationID:locationId];
  260. }
  261. return;
  262. }
  263. if (RASingleton.sharedInstance.backgroundReportType == RABackgroundReportTypeAllow) {
  264. [self reportLastLocation:[RASingleton sharedInstance].lastLocation forOrder:orderID locationID:locationId];
  265. } else if (RASingleton.sharedInstance.backgroundReportType == RABackgroundReportTypeAlwaysAsk) {
  266. [self askForReportLastLocation:orderID locationID:locationId];
  267. } else if (RASingleton.sharedInstance.backgroundReportType == RABackgroundReportTypeReject) {
  268. [self rejectReportLocationWithReason:[NSString stringWithFormat:@"Driver %@ rejected to report location",RASingleton.sharedInstance.user] forOrder:orderID locationID:locationId];
  269. }
  270. completionHandler(UIBackgroundFetchResultNewData);
  271. } else {
  272. /**
  273. {
  274. "aps" : {
  275. "alert" : {
  276. "title" : "Notification",
  277. "body" : "You have a new order"
  278. },
  279. "is-order" : 1,
  280. "order-id" : "AFS20180530001200",
  281. "order-type2" : "Pick Up",
  282. "order-type" : 2,
  283. "sound" : "default",
  284. "content-available" : 1
  285. }
  286. }
  287. */
  288. NSInteger is_order = [[aps objectForKey:@"is-order"] integerValue];
  289. if (is_order) {
  290. // 程序在前台,弹窗提示
  291. if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
  292. [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationHandleOrder object:nil userInfo:userInfo];
  293. } else {
  294. // 程序在后台,记录下来。当程序重新进入前台时弹窗提示(没有点击通知打开程序的情况)
  295. self.currentOrderNotification = userInfo;
  296. }
  297. }
  298. completionHandler(UIBackgroundFetchResultNewData);
  299. }
  300. } else {
  301. completionHandler(UIBackgroundFetchResultNoData);
  302. }
  303. }
  304. #pragma mark - Local Notification
  305. - (void)sendLocalNotification:(NSString *)title message:(NSString *)msg {
  306. // 创建Content
  307. UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
  308. content.title = title;
  309. content.body = msg;
  310. content.badge = @([UIApplication sharedApplication].applicationIconBadgeNumber + 1);
  311. // 创建Request,保证ID一致
  312. UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"local_notification" content:content trigger:nil];
  313. // 发送
  314. [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
  315. if (!error) {
  316. NSLog(@"发送本地通知:%@",request.identifier);
  317. }
  318. }];
  319. }
  320. #pragma mark - Report Location
  321. - (void)rejectReportLocationWithReason:(NSString *)reason forOrder:(NSString *)orderID locationID:(NSString *)locationId {
  322. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  323. [RADataProvider reportLocationWithUserReason:reason forOrder:orderID locationID:locationId];
  324. });
  325. }
  326. - (void)reportLastLocation:(CLLocation *)location forOrder:(NSString *)orderID locationID:(NSString *)locationId {
  327. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  328. [RADataProvider reportLastLocation:location forOrderID:orderID locationID:locationId];
  329. });
  330. }
  331. - (void)askForReportLastLocation:(NSString *)orderID locationID:(NSString *)locationId{
  332. UIViewController *topVC = self.window.rootViewController;
  333. while (topVC.presentedViewController) {
  334. topVC = topVC.presentedViewController;
  335. }
  336. if (topVC) {
  337. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"Warning" message:[NSString stringWithFormat:@"Report Location For Order:%@",orderID] preferredStyle:UIAlertControllerStyleAlert];
  338. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  339. [self rejectReportLocationWithReason:[NSString stringWithFormat:@"Driver %@ cancel to report location",RASingleton.sharedInstance.user] forOrder:orderID locationID:locationId];
  340. }];
  341. __weak typeof(self) weakSelf = self;
  342. UIAlertAction *reportAction = [UIAlertAction actionWithTitle:@"Report" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
  343. [weakSelf reportLastLocation:[RASingleton sharedInstance].lastLocation forOrder:orderID locationID:locationId];
  344. }];
  345. [alertVC addAction:cancelAction];
  346. [alertVC addAction:reportAction];
  347. [topVC presentViewController:alertVC animated:YES completion:nil];
  348. [self sendLocalNotification:@"Report Location Notification" message:[NSString stringWithFormat:@"The Apex ask your location for order:%@",orderID]];
  349. }
  350. }
  351. #pragma mark - LocationManager Delegate
  352. - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
  353. if (locations.count) {
  354. [RASingleton sharedInstance].currentLocation = [locations lastObject];
  355. [RASingleton sharedInstance].lastLocation = [locations lastObject];
  356. [RASingleton sharedInstance].lastLocationDateTime=[RAUtils current_date];
  357. NSLog(@"location: %f, %f",[RASingleton sharedInstance].currentLocation.coordinate.latitude,[RASingleton sharedInstance].currentLocation.coordinate.longitude);
  358. // 省电,停止不能超过三分钟
  359. // [self performSelector:@selector(stopLocation) withObject:nil afterDelay:10]; // 获取到位置10s后关闭位置服务
  360. // [self performSelector:@selector(startLocation) withObject:nil afterDelay:120]; // 获取到位置120s后重新打开位置服务
  361. //后台延迟定位3km,5分钟。
  362. CLLocationDistance distance = 3000;
  363. NSTimeInterval time = 60*5;
  364. [manager allowDeferredLocationUpdatesUntilTraveled:distance timeout:time];
  365. }
  366. }
  367. - (void)locationManager:(CLLocationManager *)manager
  368. didFailWithError:(NSError *)error
  369. {
  370. [RASingleton sharedInstance].currentLocation = nil;
  371. }
  372. - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
  373. if (status == kCLAuthorizationStatusDenied) {
  374. [RASingleton sharedInstance].currentLocation = nil;
  375. }
  376. }
  377. @end