AppDelegate.m 20 KB

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