AppDelegate.m 19 KB

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