// // AppDelegate.m // Apex And Drivers // // Created by Ray on 2018/5/26. // Copyright © 2018 USAI. All rights reserved. // #import "AppDelegate.h" #import #import "LoginViewController.h" #import "RAHomeViewController.h" #import static const NSInteger OrderTypeNew = 2; @interface AppDelegate () @property (nonatomic,strong) CLLocationManager *locationManager; @end @implementation AppDelegate #pragma mark - Private - (void)showHomeVCWithOrderID:(NSString *)orderID type:(NSInteger)type type2:(NSString *)type2 { RAHomeViewController *homeVC = [RAHomeViewController viewControllerFromStoryboard]; homeVC.gotoDetailID = orderID; homeVC.gotoDetailType = type; homeVC.gotoDetailType2 = type2; UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:homeVC]; self.window.rootViewController = nav; } - (void)showLoginVC { LoginViewController *rootVC = [LoginViewController viewControllerFromStoryboard]; __weak typeof(self) weakSelf = self; rootVC.loginSuccessful = ^(NSString *user,NSString *password){ [[RASingleton sharedInstance] loginUser:user password:password]; [weakSelf showHomeVCWithOrderID:nil type:OrderTypeNew type2:nil]; }; UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:rootVC]; self.window.rootViewController = nav; } - (void)saveUploadTasks { if(self.uploadManager.arr_queue!=nil) { [self.uploadManager stopAllTasks]; [self.uploadManager saveTasks]; } } - (void)startLocation { if (self.locationManager) { return; } self.locationManager = [[CLLocationManager alloc] init]; self.locationManager.delegate = self; self.locationManager.allowsBackgroundLocationUpdates = YES; self.locationManager.pausesLocationUpdatesAutomatically = NO; // 是否允许系统自动暂停定位 self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;//设置定位精度 self.locationManager.distanceFilter = 10; //不需要移动都可以刷新,不然不移动就不会执行定位,不定位的话,那么后台进程也就挂起了 [self.locationManager requestAlwaysAuthorization]; [self.locationManager startUpdatingLocation]; } - (void)stopLocation { if (self.locationManager == nil) { return; } [self.locationManager stopUpdatingLocation]; self.locationManager = nil; } - (void)reportLocation:(CLLocation *)location { if (location) { NSString *latLon = [NSString stringWithFormat:@"%f,%f",location.coordinate.latitude,location.coordinate.longitude]; [RADataProvider reportCurrentLocation:latLon]; } else { } } - (void)receiveLogoutNotification:(NSNotification *)notification { [self showLoginVC]; } - (void)receiveStartLocationNotification:(NSNotification *)notification { [self startLocation]; } - (void)receiveStopLocationNotification:(NSNotification *)notification { [self stopLocation]; } - (void)registActionNotification { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveLogoutNotification:) name:RANotificationLogout object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveStartLocationNotification:) name:RANotificationStartLocation object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveStopLocationNotification:) name:RANotificationStopLocation object:nil]; } #pragma mark - AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. NSString *orderID = nil; NSInteger orderType = OrderTypeNew; NSString *orderType2 = nil; if (launchOptions) { NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]; NSDictionary *aps = [userInfo objectForKey:@"aps"]; orderID = [aps objectForKey:@"order-id"]; orderType = [[aps objectForKey:@"order-type"] integerValue]; orderType2 = [aps objectForKey:@"order-type2"]; } // View self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds]; self.window.backgroundColor = [UIColor whiteColor]; if (RASingleton.sharedInstance.autoLogin) { [self showHomeVCWithOrderID:orderID type:orderType type2:orderType2]; } else { [self showLoginVC]; } [self.window makeKeyAndVisible]; [RASingleton.sharedInstance loadSavedReuqiredLocation]; // [self registActionNotification]; //消息推送注册 UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter]; [center setDelegate:self]; UNAuthorizationOptions type = UNAuthorizationOptionBadge|UNAuthorizationOptionSound|UNAuthorizationOptionAlert; [center requestAuthorizationWithOptions:type completionHandler:^(BOOL granted, NSError * _Nullable error) { if (granted) { NSLog(@"推送通知授权成功"); }else{ NSLog(@"推送通知授权失败"); } }]; [application registerForRemoteNotifications]; return YES; } - (void)applicationDidBecomeActive:(UIApplication *)application { if (!self.uploadManager) { self.uploadManager=[[RAUploadManager alloc] init]; } } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. [self saveUploadTasks]; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } #pragma mark - Notification //完成注册后收到devicetoken - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { //上传deviceToken给后台服务器 NSString *fullStr = [deviceToken description]; NSLog(@"fullstr= %@",fullStr); NSString *deviceTokenStr = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""]; NSLog(@"deviceTokenStr:\n%@",deviceTokenStr); [[RASingleton sharedInstance] setNotificationToken:deviceTokenStr]; } - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { NSLog(@"注册推送失败:%@",error); } //处理通知 - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { // 程序在前台收到通知 UNNotificationRequest *request = notification.request; NSDictionary *userInfo = request.content.userInfo; if ([request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) { NSLog(@"收到远程通知: %@",userInfo); } else { NSLog(@"收到本地通知: %@",userInfo); } // UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert completionHandler(UNNotificationPresentationOptionNone); } - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler { NSLog(@"接收到推送内容==%@", response.notification.request.content.userInfo); // 点击通知 NSDictionary *userInfo = response.notification.request.content.userInfo; NSDictionary *aps = [userInfo objectForKey:@"aps"]; NSString *orderID = [aps objectForKey:@"order-id"]; NSInteger orderType = [[aps objectForKey:@"order-type"] integerValue]; NSString *orderType2 = [aps objectForKey:@"order-type2"]; if (!orderType2) { orderType2 = @""; } if (orderID) { [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationGoDetail object:@{@"orderID" : orderID,@"orderType" : @(orderType),@"orderType2" : orderType2}]; } completionHandler(); } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { /** 静默推送alert为空 { "aps" : { "alert" : "", "content-available" : 1 } } */ // "content-available" : 1 收到通知 NSLog(@"收到静默推送: %@",userInfo); if (userInfo) { NSDictionary *aps = [userInfo objectForKey:@"aps"]; NSInteger report_location = [[aps objectForKey:@"report-location"] integerValue]; if (report_location == 1) { [self reportLocation:[RASingleton sharedInstance].currentLocation]; completionHandler(UIBackgroundFetchResultNewData); } else { /** { "aps" : { "alert" : { "title" : "Notification", "body" : "You have a new order" }, "new-order" : 1, "order-id" : "AFS20180530001200", "order-type2" : "Pick Up", "order-type" : 2, "sound" : "default", "content-available" : 1 } } */ NSInteger new_order = [[aps objectForKey:@"new-order"] integerValue]; if (new_order) { [[NSNotificationCenter defaultCenter] postNotificationName:RANotificationNewOrder object:nil]; } completionHandler(UIBackgroundFetchResultNewData); } } else { completionHandler(UIBackgroundFetchResultNoData); } } #pragma mark - LocationManager Delegate - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { if (locations.count) { [RASingleton sharedInstance].currentLocation = [locations lastObject]; NSLog(@"location: %f, %f",[RASingleton sharedInstance].currentLocation.coordinate.latitude,[RASingleton sharedInstance].currentLocation.coordinate.longitude); // 省电,停止不能超过三分钟 // [self performSelector:@selector(stopLocation) withObject:nil afterDelay:10]; // 获取到位置10s后关闭位置服务 // [self performSelector:@selector(startLocation) withObject:nil afterDelay:120]; // 获取到位置120s后重新打开位置服务 CLLocationDistance distance = 500; NSTimeInterval time = 60; [manager allowDeferredLocationUpdatesUntilTraveled:distance timeout:time]; } } - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { if (status == kCLAuthorizationStatusDenied) { [RASingleton sharedInstance].currentLocation = nil; } } @end