AppDelegate.m 14 KB

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