AppDelegate.m 15 KB

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