AppDelegate.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 {
  65. if (location) {
  66. NSString *latLon = [NSString stringWithFormat:@"%f,%f",location.coordinate.latitude,location.coordinate.longitude];
  67. [RADataProvider reportCurrentLocation:latLon];
  68. } else {
  69. }
  70. }
  71. - (void)receiveLogoutNotification:(NSNotification *)notification {
  72. [self showLoginVC];
  73. }
  74. - (void)receiveStartLocationNotification:(NSNotification *)notification {
  75. [self startLocation];
  76. }
  77. - (void)receiveStopLocationNotification:(NSNotification *)notification {
  78. [self stopLocation];
  79. }
  80. - (void)registActionNotification {
  81. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveLogoutNotification:) name:RANotificationLogout object:nil];
  82. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveStartLocationNotification:) name:RANotificationStartLocation object:nil];
  83. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveStopLocationNotification:) name:RANotificationStopLocation object:nil];
  84. }
  85. #pragma mark - AppDelegate
  86. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  87. // Override point for customization after application launch.
  88. NSString *orderID = nil;
  89. NSInteger orderType = OrderTypeNew;
  90. NSString *orderType2 = nil;
  91. if (launchOptions) {
  92. NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
  93. NSDictionary *aps = [userInfo objectForKey:@"aps"];
  94. orderID = [aps objectForKey:@"order-id"];
  95. orderType = [[aps objectForKey:@"order-type"] integerValue];
  96. orderType2 = [aps objectForKey:@"order-type2"];
  97. }
  98. // View
  99. self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  100. self.window.backgroundColor = [UIColor whiteColor];
  101. if (RASingleton.sharedInstance.autoLogin) {
  102. [self showHomeVCWithOrderID:orderID type:orderType type2:orderType2];
  103. } else {
  104. [self showLoginVC];
  105. }
  106. [self.window makeKeyAndVisible];
  107. [RASingleton.sharedInstance loadSavedReuqiredLocation];
  108. //
  109. [self registActionNotification];
  110. //消息推送注册
  111. UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter];
  112. [center setDelegate:self];
  113. UNAuthorizationOptions type = UNAuthorizationOptionBadge|UNAuthorizationOptionSound|UNAuthorizationOptionAlert;
  114. [center requestAuthorizationWithOptions:type completionHandler:^(BOOL granted, NSError * _Nullable error) {
  115. if (granted) {
  116. NSLog(@"推送通知授权成功");
  117. }else{
  118. NSLog(@"推送通知授权失败");
  119. }
  120. }];
  121. [application registerForRemoteNotifications];
  122. return YES;
  123. }
  124. - (void)applicationDidBecomeActive:(UIApplication *)application {
  125. if (!self.uploadManager) {
  126. self.uploadManager=[[RAUploadManager alloc] init];
  127. }
  128. }
  129. - (void)applicationWillTerminate:(UIApplication *)application {
  130. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  131. [self saveUploadTasks];
  132. }
  133. - (void)dealloc {
  134. [[NSNotificationCenter defaultCenter] removeObserver:self];
  135. }
  136. #pragma mark - Notification
  137. //完成注册后收到devicetoken
  138. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  139. //上传deviceToken给后台服务器
  140. NSString *fullStr = [deviceToken description];
  141. NSLog(@"fullstr= %@",fullStr);
  142. NSString *deviceTokenStr = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
  143. NSLog(@"deviceTokenStr:\n%@",deviceTokenStr);
  144. [[RASingleton sharedInstance] setNotificationToken:deviceTokenStr];
  145. }
  146. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  147. NSLog(@"注册推送失败:%@",error);
  148. }
  149. //处理通知
  150. - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
  151. // 程序在前台收到通知
  152. UNNotificationRequest *request = notification.request;
  153. NSDictionary *userInfo = request.content.userInfo;
  154. if ([request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
  155. NSLog(@"收到远程通知: %@",userInfo);
  156. } else {
  157. NSLog(@"收到本地通知: %@",userInfo);
  158. }
  159. // UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert
  160. completionHandler(UNNotificationPresentationOptionNone);
  161. }
  162. - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
  163. NSLog(@"接收到推送内容==%@", response.notification.request.content.userInfo);
  164. // 点击通知
  165. NSDictionary *userInfo = response.notification.request.content.userInfo;
  166. NSDictionary *aps = [userInfo objectForKey:@"aps"];
  167. NSString *orderID = [aps objectForKey:@"order-id"];
  168. NSInteger orderType = [[aps objectForKey:@"order-type"] integerValue];
  169. NSString *orderType2 = [aps objectForKey:@"order-type2"];
  170. if (!orderType2) {
  171. orderType2 = @"";
  172. }
  173. if (orderID) {
  174. [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationGoDetail object:@{@"orderID" : orderID,@"orderType" : @(orderType),@"orderType2" : orderType2}];
  175. }
  176. completionHandler();
  177. }
  178. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  179. /**
  180. 静默推送alert为空
  181. {
  182. "aps" : {
  183. "alert" : "",
  184. "content-available" : 1
  185. }
  186. }
  187. */
  188. // "content-available" : 1 收到通知
  189. NSLog(@"收到静默推送: %@",userInfo);
  190. if (userInfo) {
  191. NSDictionary *aps = [userInfo objectForKey:@"aps"];
  192. NSInteger report_location = [[aps objectForKey:@"report-location"] integerValue];
  193. if (report_location == 1) {
  194. [self reportLocation:[RASingleton sharedInstance].currentLocation];
  195. completionHandler(UIBackgroundFetchResultNewData);
  196. } else {
  197. /**
  198. {
  199. "aps" : {
  200. "alert" : {
  201. "title" : "Notification",
  202. "body" : "You have a new order"
  203. },
  204. "new-order" : 1,
  205. "order-id" : "AFS20180530001200",
  206. "order-type2" : "Pick Up",
  207. "order-type" : 2,
  208. "sound" : "default",
  209. "content-available" : 1
  210. }
  211. }
  212. */
  213. NSInteger new_order = [[aps objectForKey:@"new-order"] integerValue];
  214. if (new_order) {
  215. [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationNewOrder object:nil];
  216. }
  217. completionHandler(UIBackgroundFetchResultNewData);
  218. }
  219. } else {
  220. completionHandler(UIBackgroundFetchResultNoData);
  221. }
  222. }
  223. #pragma mark - LocationManager Delegate
  224. - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
  225. if (locations.count) {
  226. [RASingleton sharedInstance].currentLocation = [locations lastObject];
  227. NSLog(@"location: %f, %f",[RASingleton sharedInstance].currentLocation.coordinate.latitude,[RASingleton sharedInstance].currentLocation.coordinate.longitude);
  228. // 省电,停止不能超过三分钟
  229. // [self performSelector:@selector(stopLocation) withObject:nil afterDelay:10]; // 获取到位置10s后关闭位置服务
  230. // [self performSelector:@selector(startLocation) withObject:nil afterDelay:120]; // 获取到位置120s后重新打开位置服务
  231. CLLocationDistance distance = 500;
  232. NSTimeInterval time = 60;
  233. [manager allowDeferredLocationUpdatesUntilTraveled:distance timeout:time];
  234. }
  235. }
  236. - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
  237. if (status == kCLAuthorizationStatusDenied) {
  238. [RASingleton sharedInstance].currentLocation = nil;
  239. }
  240. }
  241. @end