AppDelegate.m 19 KB

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