AppDelegate.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. static const NSInteger OrderTypeNew = 2;
  14. @interface AppDelegate ()<UNUserNotificationCenterDelegate,CLLocationManagerDelegate>
  15. @property (nonatomic,strong) CLLocationManager *locationManager;
  16. @end
  17. @implementation AppDelegate
  18. #pragma mark - Private
  19. - (void)showHomeVCWithOrderID:(NSString *)orderID type:(NSInteger)type type2:(NSString *)type2 {
  20. RAHomeViewController *homeVC = [RAHomeViewController viewControllerFromStoryboard];
  21. homeVC.gotoDetailID = orderID;
  22. homeVC.gotoDetailType = type;
  23. homeVC.gotoDetailType2 = type2;
  24. UINavigationController *nav = [[UINavigationController 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 showHomeVCWithOrderID:nil type:OrderTypeNew type2:nil];
  33. };
  34. UINavigationController *nav = [[UINavigationController 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)startLocation {
  45. if (self.locationManager) {
  46. return;
  47. }
  48. self.locationManager = [[CLLocationManager alloc] init];
  49. self.locationManager.delegate = self;
  50. self.locationManager.allowsBackgroundLocationUpdates = YES;
  51. self.locationManager.pausesLocationUpdatesAutomatically = NO; // 是否允许系统自动暂停定位
  52. self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;//设置定位精度
  53. self.locationManager.distanceFilter = 10; //不需要移动都可以刷新,不然不移动就不会执行定位,不定位的话,那么后台进程也就挂起了
  54. [self.locationManager requestAlwaysAuthorization];
  55. [self.locationManager startUpdatingLocation];
  56. }
  57. - (void)stopLocation {
  58. if (self.locationManager == nil) {
  59. return;
  60. }
  61. [self.locationManager stopUpdatingLocation];
  62. self.locationManager = nil;
  63. }
  64. - (void)reportLocation:(CLLocation *)location forOrder:(NSString *)orderID {
  65. if (location) {
  66. NSString *latLon = [NSString stringWithFormat:@"%f,%f",location.coordinate.latitude,location.coordinate.longitude];
  67. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  68. [RADataProvider reportCurrentLocation:latLon forOrderID:orderID];
  69. });
  70. } else {
  71. }
  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. // View
  101. self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  102. self.window.backgroundColor = [UIColor whiteColor];
  103. if (RASingleton.sharedInstance.autoLogin) {
  104. [self showHomeVCWithOrderID:orderID type:orderType type2:orderType2];
  105. } else {
  106. [self showLoginVC];
  107. }
  108. [self.window makeKeyAndVisible];
  109. [RASingleton.sharedInstance loadSavedReuqiredLocation];
  110. //
  111. [self registActionNotification];
  112. //消息推送注册
  113. UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter];
  114. [center setDelegate:self];
  115. UNAuthorizationOptions type = UNAuthorizationOptionBadge|UNAuthorizationOptionSound|UNAuthorizationOptionAlert;
  116. [center requestAuthorizationWithOptions:type completionHandler:^(BOOL granted, NSError * _Nullable error) {
  117. if (granted) {
  118. NSLog(@"推送通知授权成功");
  119. }else{
  120. NSLog(@"推送通知授权失败");
  121. }
  122. }];
  123. [application registerForRemoteNotifications];
  124. return YES;
  125. }
  126. - (void)applicationDidBecomeActive:(UIApplication *)application {
  127. if (!self.uploadManager) {
  128. self.uploadManager=[[RAUploadManager alloc] init];
  129. }
  130. }
  131. - (void)applicationWillTerminate:(UIApplication *)application {
  132. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  133. [self saveUploadTasks];
  134. }
  135. - (void)dealloc {
  136. [[NSNotificationCenter defaultCenter] removeObserver:self];
  137. }
  138. #pragma mark - Notification
  139. //完成注册后收到devicetoken
  140. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  141. //上传deviceToken给后台服务器
  142. NSString *fullStr = [deviceToken description];
  143. NSLog(@"fullstr= %@",fullStr);
  144. NSString *deviceTokenStr = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
  145. NSLog(@"deviceTokenStr:\n%@",deviceTokenStr);
  146. [[RASingleton sharedInstance] setNotificationToken:deviceTokenStr];
  147. }
  148. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  149. NSLog(@"注册推送失败:%@",error);
  150. }
  151. //处理通知
  152. - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
  153. // 程序在前台收到通知
  154. UNNotificationRequest *request = notification.request;
  155. NSDictionary *userInfo = request.content.userInfo;
  156. if ([request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
  157. NSLog(@"收到远程通知: %@",userInfo);
  158. } else {
  159. NSLog(@"收到本地通知: %@",userInfo);
  160. }
  161. // UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert
  162. completionHandler(UNNotificationPresentationOptionNone);
  163. }
  164. - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
  165. NSLog(@"接收到推送内容==%@", response.notification.request.content.userInfo);
  166. // 点击通知
  167. NSDictionary *userInfo = response.notification.request.content.userInfo;
  168. NSDictionary *aps = [userInfo objectForKey:@"aps"];
  169. NSString *orderID = [aps objectForKey:@"order-id"];
  170. NSInteger orderType = [[aps objectForKey:@"order-type"] integerValue];
  171. NSString *orderType2 = [aps objectForKey:@"order-type2"];
  172. if (!orderType2) {
  173. orderType2 = @"";
  174. }
  175. if (orderID) {
  176. [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationGoDetail object:@{@"orderID" : orderID,@"orderType" : @(orderType),@"orderType2" : orderType2}];
  177. }
  178. completionHandler();
  179. }
  180. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  181. /**
  182. 静默推送alert为空
  183. {
  184. "aps" : {
  185. "alert" : "",
  186. "content-available" : 1
  187. }
  188. }
  189. */
  190. // "content-available" : 1 收到通知
  191. NSLog(@"收到静默推送: %@",userInfo);
  192. if (userInfo) {
  193. NSDictionary *aps = [userInfo objectForKey:@"aps"];
  194. NSInteger report_location = [[aps objectForKey:@"report-location"] integerValue];
  195. if (report_location == 1) {
  196. NSString *orderID = [aps objectForKey:@"order-id"];
  197. [self reportLocation:[RASingleton sharedInstance].currentLocation forOrder:orderID];
  198. completionHandler(UIBackgroundFetchResultNewData);
  199. } else {
  200. /**
  201. {
  202. "aps" : {
  203. "alert" : {
  204. "title" : "Notification",
  205. "body" : "You have a new order"
  206. },
  207. "new-order" : 1,
  208. "order-id" : "AFS20180530001200",
  209. "order-type2" : "Pick Up",
  210. "order-type" : 2,
  211. "sound" : "default",
  212. "content-available" : 1
  213. }
  214. }
  215. */
  216. NSInteger new_order = [[aps objectForKey:@"new-order"] integerValue];
  217. if (new_order) {
  218. [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationNewOrder object:nil];
  219. }
  220. completionHandler(UIBackgroundFetchResultNewData);
  221. }
  222. } else {
  223. completionHandler(UIBackgroundFetchResultNoData);
  224. }
  225. }
  226. #pragma mark - LocationManager Delegate
  227. - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
  228. if (locations.count) {
  229. [RASingleton sharedInstance].currentLocation = [locations lastObject];
  230. NSLog(@"location: %f, %f",[RASingleton sharedInstance].currentLocation.coordinate.latitude,[RASingleton sharedInstance].currentLocation.coordinate.longitude);
  231. // 省电,停止不能超过三分钟
  232. // [self performSelector:@selector(stopLocation) withObject:nil afterDelay:10]; // 获取到位置10s后关闭位置服务
  233. // [self performSelector:@selector(startLocation) withObject:nil afterDelay:120]; // 获取到位置120s后重新打开位置服务
  234. CLLocationDistance distance = 500;
  235. NSTimeInterval time = 60;
  236. [manager allowDeferredLocationUpdatesUntilTraveled:distance timeout:time];
  237. }
  238. }
  239. - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
  240. if (status == kCLAuthorizationStatusDenied) {
  241. [RASingleton sharedInstance].currentLocation = nil;
  242. }
  243. }
  244. @end