@xiasiwole
2018-05-24T03:26:08.000000Z
字数 136544
阅读 1097
萌呗
#pragma mark 禁止横屏- (UIInterfaceOrientationMask )application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{return UIInterfaceOrientationMaskPortrait;}- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {// Override point for customization after application launch.//APP主window配置self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];self.window.backgroundColor = [UIColor whiteColor];UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];UINavigationController *homeVc = [sb instantiateViewControllerWithIdentifier:@"homeNav"];self.window.rootViewController = homeVc;[self.window makeKeyAndVisible];//高德地图appkey配置[AMapServices sharedServices].apiKey = kMapApikey;//开始定位[[LocationManager sharedLocationManager] startLoction];//微信支付[WXApi registerApp:kWXAppId];//极光推送//notice: 3.0.0及以后版本注册可以这样写,也可以继续用之前的注册方式JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {// 可以添加自定义categories// NSSet<UNNotificationCategory *> *categories for iOS10 or later// NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9}[JPUSHService registerForRemoteNotificationConfig:entity delegate:self];//如不需要使用IDFA,advertisingIdentifier 可为nil[JPUSHService setupWithOption:launchOptions appKey:kJPushAppkeychannel:@"app store"apsForProduction:YESadvertisingIdentifier:nil];// 获取自定义消息推送内容NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];[defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];[JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {NSLog(@"resCode : %d,registrationID: %@",resCode,registrationID);if (registrationID) {[self sendRegistrationID:registrationID];}}];[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];return YES;}- (void)sendRegistrationID:(NSString *)registrationID{NSString *url = [kBaseUrl stringByAppendingPathComponent:@"i/member/setJPush"];[CommonUtils sendPOST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {[formData appendPartWithFormData:[registrationID dataUsingEncoding:NSUTF8StringEncoding] name:@"clientid"];[formData appendPartWithFormData:[@"2" dataUsingEncoding:NSUTF8StringEncoding] name:@"clientos"];} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {NSLog(@"%@",responseObject);} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {NSLog(@"%@",error);}];}- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {if ([url.description hasPrefix:@"wx"]) {return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];}if ([url.host isEqualToString:@"safepay"]) {// 支付跳转支付宝钱包进行支付,处理支付结果// [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {// }];}return YES;}// NOTE: 9.0以后使用新API接口- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options{if ([url.description hasPrefix:@"wx"]) {return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];}if ([url.host isEqualToString:@"safepay"]) {// 支付跳转支付宝钱包进行支付,处理支付结果// [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {// NSLog(@"result4444 = %@",resultDic);// NSString *statusCode = resultDic[@"resultStatus"];//// }];}return YES;}//推送- (void)application:(UIApplication *)applicationdidRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {/// Required - 注册 DeviceToken[JPUSHService registerDeviceToken:deviceToken];}- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {//OptionalNSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);}#pragma mark- JPUSHRegisterDelegate//APNS推送(APP退出的时候)- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {// 取得 APNs 标准信息内容NSDictionary *aps = [userInfo valueForKey:@"aps"];NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量NSString *sound = [aps valueForKey:@"sound"]; //播放的声音// []// 取得Extras字段内容NSString *customizeField1 = [userInfo valueForKey:@"customizeExtras"]; //服务端中Extras字段,key是自己定义的NSLog(@"content =[%@], badge=[%d], sound=[%@], customize field =[%@]",content,badge,sound,customizeField1);// iOS 10 以下 Required[JPUSHService handleRemoteNotification:userInfo];}//iOS 7 Remote Notification- (void)application:(UIApplication *)application didReceiveRemoteNotification: (NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {NSLog(@"this is iOS7 Remote Notification");// iOS 10 以下 Required[JPUSHService handleRemoteNotification:userInfo];completionHandler(UIBackgroundFetchResultNewData);}#pragma mark- JPUSHRegisterDelegate // 2.1.9版新增JPUSHRegisterDelegate,需实现以下两个方法// iOS 10 Support- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {// RequiredNSDictionary * userInfo = notification.request.content.userInfo;if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {[JPUSHService handleRemoteNotification:userInfo];}else {// 本地通知}completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以选择设置}// iOS 10 Support- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler: (void (^)())completionHandler {// RequiredNSDictionary * userInfo = response.notification.request.content.userInfo;if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {[JPUSHService handleRemoteNotification:userInfo];}else {// 本地通知}completionHandler(); // 系统要求执行这个方法}//获取自定义消息推送内容(长连接 APP启动中)- (void)networkDidReceiveMessage:(NSNotification *)notification {NSDictionary * userInfo = [notification userInfo];NSString *content = [userInfo valueForKey:@"content"];NSString *messageID = [userInfo valueForKey:@"_j_msgid"];NSDictionary *extras = [userInfo valueForKey:@"extras"];NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的Extras附加字段,key是自己定义的// if ([LCBluetoothManager sharedManager].conectedState == ConnectedState) {// //蓝牙正在连接车子// }else{// [[NSNotificationCenter defaultCenter] postNotificationName:@"closeLockByNoti" object:nil userInfo:extras];// }NSLog(@"通知:%@",userInfo);}
#import "HomeViewController.h"/**地图*/#import "System.h"#import "SettingView.h"#import "UserTableViewController.h"#import "Service1ViewController.h"#import "Service2ViewController.h"#import "Service3ViewController.h"#import "Service4ViewController.h"#import "ScanViewController.h"#import "StyleDIY.h"#import "Account.h"#import "LoginViewController.h"#import "DepositViewController.h"#import <CoreBluetooth/CoreBluetooth.h>#import "CommonUtils.h"#import "WalletViewController.h"#import "Login.h"#import "AuthViewController.h"#import "Home.h"#import "BusinessArea.h"//高得地图#import "Map.h"#import <MAMapKit/MAMapKit.h>#import <AMapFoundationKit/AMapFoundationKit.h>#import <AMapLocationKit/AMapLocationKit.h>#import "CostViewController.h"#import "LCBluetoothManager.h"#import "LocationManager.h"#import "WebViewController.h"#import "MessageTableViewController.h"@interface HomeViewController ()<SettingViewDelegate,MAMapViewDelegate,CLLocationManagerDelegate,AMapGeoFenceManagerDelegate>//地理围栏@property (nonatomic,strong) AMapGeoFenceManager *geoFenceManager;@property (nonatomic,strong) MAMapView *mapView;@property (weak, nonatomic) IBOutlet UIView *mapBackView;@property (weak, nonatomic) IBOutlet UIButton *CurrentBtn;@property (weak, nonatomic) IBOutlet UIButton *settingBtn;@property (weak, nonatomic) IBOutlet UIButton *refreshBtn;@property (weak, nonatomic) IBOutlet UIButton *userBtn;@property (weak, nonatomic) IBOutlet UIButton *scanBtn;@property (nonatomic,strong) UIImageView *locationImage;@property (nonatomic,strong) SettingView *settingView;@property (nonatomic) BOOL showSettingView;@property (weak, nonatomic) IBOutlet UILabel *depositLabel;@property (weak, nonatomic) IBOutlet UIView *tipView;@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topMargin;//商圈@property (nonatomic,strong) NSMutableArray <BusinessArea *> *areaArr;@property (weak, nonatomic) IBOutlet UILabel *titleLab;//用车@property (weak, nonatomic) IBOutlet UIView *useView;@property (weak, nonatomic) IBOutlet NSLayoutConstraint *useViewHeight;@property (weak, nonatomic) IBOutlet UILabel *time;@property (weak, nonatomic) IBOutlet UILabel *distance;@property (weak, nonatomic) IBOutlet UILabel *heat;@property (weak, nonatomic) IBOutlet UIButton *lockBtn;@property (weak, nonatomic) IBOutlet UILabel *lockNo;@property (weak, nonatomic) IBOutlet UILabel *cost;@property (nonatomic,strong) NSTimer *rentTimer;//蓝牙状态@property (nonatomic, strong) MAAnnotationView *userLocationAnnotationView;@end#define kUseViewHeight 160@implementation HomeViewController- (void)viewDidLoad {[super viewDidLoad];//初始化地图[self configMapView];//初始化地理围栏[self initGeoFenceManager];//其他视图设置[self setOtherView];//蓝牙检测[LCBluetoothManager sharedManager];//旧令牌获取新令牌if ([[Account shareAccount] isLogin]) {[self getAuth];}//获取商圈[self getBusinessArea];[self configUserView];[self getRent];[self requestMemberInfo];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(openSuccess) name:kOpenLockSuccess object:nil];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closeLock:) name:kCloseLock object:nil];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSkip:) name:@"closeLockByNoti" object:nil];[self drawColor];}-(void)viewDidAppear:(BOOL)animated{[super viewDidAppear:animated];_mapView.showsUserLocation = YES;// _mapView.userTrackingMode = MAUserTrackingModeFollowWithHeading;}-(void)viewWillAppear:(BOOL)animated{[super viewWillAppear:animated];self.navigationController.navigationBar.hidden = YES;if ([[Account shareAccount].user.hasdeposit integerValue] == 1) {_tipView.hidden = YES;}else{_tipView.hidden = NO;}}- (void)notificationSkip:(NSNotification *)noti{[self skipFee:noti.userInfo];}- (void)openSuccess{_useViewHeight.constant = kUseViewHeight;_useView.hidden = NO;[self getRent];}#pragma mark - 视图配置- (void)drawColor{CAGradientLayer *gradientLayer = [CAGradientLayer layer];UIColor *beginColor = [UIColor colorWithRed:210.f/255.f green:20/255.f blue:25.f/255.f alpha:1];UIColor *endColor = [UIColor colorWithRed:240.f/255.f green:130.f/255.f blue:45.f/255.f alpha:1];gradientLayer.colors = @[(__bridge id)beginColor.CGColor, (__bridge id)endColor.CGColor];gradientLayer.locations = @[@0.1,@1.0];gradientLayer.startPoint = CGPointMake(0, 0);gradientLayer.endPoint = CGPointMake(1.0, 0);gradientLayer.frame = _tipView.bounds;[self.tipView.layer addSublayer:gradientLayer];[self.tipView bringSubviewToFront:self.tipView.subviews.firstObject];[self.tipView bringSubviewToFront:_depositLabel];CAGradientLayer *gradientLayer2 = [CAGradientLayer layer];gradientLayer2.colors = @[(__bridge id)beginColor.CGColor, (__bridge id)endColor.CGColor];gradientLayer2.locations = @[@0.1,@1.0];gradientLayer2.startPoint = CGPointMake(0, 0);gradientLayer2.endPoint = CGPointMake(1, 0);gradientLayer2.frame = CGRectMake(0, 0, kScreenW, _scanBtn.bounds.size.height);// _scanBtn.bounds;[self.scanBtn.layer addSublayer:gradientLayer2];[self.scanBtn bringSubviewToFront:_scanBtn.imageView];// self.scanBtn.layer bri}- (void)configMapView{[AMapServices sharedServices].enableHTTPS = YES;_mapView = [[MAMapView alloc] initWithFrame:_mapBackView.bounds];[_mapBackView addSubview:_mapView];//显示定位小蓝点_mapView.showsUserLocation = YES;_mapView.userTrackingMode = MAUserTrackingModeFollow;_mapView.delegate = self;// self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;_mapView.zoomLevel = 17;_mapView.minZoomLevel = 10;_mapView.showsCompass = NO;// _mapView.rotateEnabled = NO;// _mapView.rotateCameraEnabled = NO;MAUserLocationRepresentation *r = [[MAUserLocationRepresentation alloc] init];r.showsAccuracyRing = NO;///精度圈是否显示,默认YESr.showsHeadingIndicator = YES;///是否显示方向指示(MAUserTrackingModeFollowWithHeading模式开启)。默认为YESr.fillColor = [UIColor redColor];///精度圈 填充颜色, 默认 kAccuracyCircleDefaultColorr.strokeColor = [UIColor blueColor];///精度圈 边线颜色, 默认 kAccuracyCircleDefaultColorr.lineWidth = 2;///精度圈 边线宽度,默认0r.enablePulseAnnimation = YES;///内部蓝色圆点是否使用律动效果, 默认YES// r.locationDotBgColor = [UIColor greenColor];///定位点背景色,不设置默认白色// r.locationDotFillColor = [UIColor grayColor];///定位点蓝色圆点颜色,不设置默认蓝色r.image = [UIImage imageNamed:@"userPosition"];[self.mapView updateUserLocationRepresentation:r];}- (void)setOtherView{[self.view bringSubviewToFront:_settingBtn];[self.view bringSubviewToFront:_CurrentBtn];[self.view bringSubviewToFront:_refreshBtn];[self.view bringSubviewToFront:_userBtn];[self.view bringSubviewToFront:_scanBtn];_scanBtn.layer.cornerRadius = 30;_scanBtn.clipsToBounds = YES;_userBtn.layer.cornerRadius = 20;_userBtn.clipsToBounds = YES;_settingBtn.layer.cornerRadius = 20;_settingBtn.clipsToBounds = YES;_CurrentBtn.layer.cornerRadius = 20;_CurrentBtn.clipsToBounds = YES;_settingView = [[NSBundle mainBundle] loadNibNamed:@"SettingView" owner:nil options:nil][0];_settingView.frame = CGRectMake(20, kScreenH-250, kScreenW-40,220 );[self.view addSubview:_settingView];_settingView.hidden = YES;_settingView.layer.cornerRadius = 20;_settingView.clipsToBounds = YES;_settingView.delegate = self;_locationImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"location_start"]];_locationImage.bounds = CGRectMake(0, 0, 20, 40);_locationImage.center = self.view.center;[self.view addSubview:_locationImage];[self.view bringSubviewToFront:_locationImage];//tipView_depositLabel.layer.cornerRadius = 10;_depositLabel.clipsToBounds = YES;[self.view bringSubviewToFront:_tipView];UITapGestureRecognizer *tapGestureRecognizer1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(skipDeposit)];[self.tipView addGestureRecognizer:tapGestureRecognizer1];self.tipView.userInteractionEnabled = YES;}//在地图上绘制点标记- (void)addPointToMapviewWithLatitude:(NSString *)latitude longitude:(NSString *)longitude{MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];pointAnnotation.coordinate = CLLocationCoordinate2DMake([latitude doubleValue], [longitude doubleValue]);[_mapView addAnnotation:pointAnnotation];}- (void)configUserView{[_lockBtn.layer setBorderColor: [UIColor blackColor].CGColor];[_lockBtn.layer setBorderWidth:1];_lockBtn.layer.cornerRadius = 4;_lockBtn.clipsToBounds = YES;_useViewHeight.constant = 0;_useView.hidden = YES;_titleLab.hidden = YES;}- (void)updateUserView:(NSDictionary *)dic{//隐藏扫码按钮_scanBtn.hidden = YES;_titleLab.hidden = NO;_useViewHeight.constant = kUseViewHeight;_useView.hidden = NO;float time = [CommonUtils getDifSinceNowWithTimetamp:dic[@"createtime"]];float dif = time/1000/60;_time.text = [NSString stringWithFormat:@"%.f分",dif];_lockNo.text = [NSString stringWithFormat:@"正在用车:%@",dic[@"lockno"]];_cost.text = [NSString stringWithFormat:@"预计花费:%.f元",[dic[@"cost"] floatValue]/100];MAMapPoint point1 = MAMapPointForCoordinate(CLLocationCoordinate2DMake([LocationManager sharedLocationManager].latitude,[LocationManager sharedLocationManager].longitude));NSArray *temArr = [dic[@"rentposition"] componentsSeparatedByString:@","];MAMapPoint point2 = MAMapPointForCoordinate(CLLocationCoordinate2DMake([temArr[0] floatValue],[temArr[1] floatValue]));//2.计算距离CLLocationDistance distance = MAMetersBetweenMapPoints(point1,point2)/1000.f;_distance.text = [NSString stringWithFormat:@"%.2fkm",distance];_heat.text = [NSString stringWithFormat:@"%.2f大卡",distance *8];// _heat.text = dic[@""];}- (void)initGeoFenceManager{[AMapServices sharedServices].apiKey = kMapApikey;self.geoFenceManager = [[AMapGeoFenceManager alloc] init];self.geoFenceManager.delegate = self;self.geoFenceManager.activeAction = AMapGeoFenceActiveActionInside | AMapGeoFenceActiveActionOutside | AMapGeoFenceActiveActionStayed; //设置希望侦测的围栏触发行为,默认是侦测用户进入围栏的行为,即AMapGeoFenceActiveActionInside,这边设置为进入,离开,停留(在围栏内10分钟以上),都触发回调self.geoFenceManager.allowsBackgroundLocationUpdates = YES;}- (void)skipFee:(NSDictionary *)dic{[_rentTimer invalidate];_scanBtn.hidden = NO;_titleLab.hidden = YES;_rentTimer = nil;_useViewHeight.constant = 0;_useView.hidden = YES;UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];CostViewController *vc = [sb instantiateViewControllerWithIdentifier:@"cost"];vc.fee = dic[@"fee"];vc.useTime = dic[@"useTime"];[self.navigationController pushViewController:vc animated:YES];}#pragma mark - 网络请求//获取车锁- (void)getLocksWithFenceId:(NSString *)fenceid{NSString *url = [kBaseUrl stringByAppendingPathComponent:kGetLocks];NSString *SIGN = [CommonUtils getSign];NSString *AUTH = [Account shareAccount].user.auth;AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {[formData appendPartWithFormData:[fenceid dataUsingEncoding:NSUTF8StringEncoding] name:@"fenceid"];} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {NSLog(@"%@",responseObject);//绘制点标记NSString *status = responseObject[@"status"];if ([status integerValue] == 1) {for (NSDictionary *dic in responseObject[@"data"]) {[self addPointToMapviewWithLatitude:dic[@"latitude"] longitude:dic[@"longitude"]];}}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {NSLog(@"%@",error);}];}- (void)closeLock:(NSNotification *)noti{[[LCBluetoothManager sharedManager] cancelPeripheralConnection];[[LocationManager sharedLocationManager] stopSaveRoute];;NSString *url = [kBaseUrl stringByAppendingPathComponent:kReturnLock];NSString *SIGN = [CommonUtils getSign];NSString *AUTH = [Account shareAccount].user.auth;AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {//参数[formData appendPartWithFormData:[noti.userInfo[@"rentid"] dataUsingEncoding:NSUTF8StringEncoding] name:@"rentid"];[formData appendPartWithFormData:[noti.userInfo[@"lockno"] dataUsingEncoding:NSUTF8StringEncoding] name:@"lockno"];LocationManager *locationManager = [LocationManager sharedLocationManager];// 归还地点的坐标 经度,纬度NSString *returnposition = [NSString stringWithFormat:@"%f,%f",locationManager.latitude,locationManager.longitude];[formData appendPartWithFormData:[returnposition dataUsingEncoding:NSUTF8StringEncoding] name:@"returnposition"];// 行迹坐标集 经度,纬度NSString *tem = locationManager.route;NSLog(@"行迹坐标集 经度,纬度:%@",tem);if (tem != nil) {[formData appendPartWithFormData:[locationManager.route dataUsingEncoding:NSUTF8StringEncoding] name:@"route"];}} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {[CommonUtils hideHudForView:self.view];NSLog(@"%@",responseObject);NSString *status = responseObject[@"status"];NSString *msg = responseObject[@"msg"];if ([status integerValue] == 1) {[self skipFee:responseObject[@"data"]];[[NSUserDefaults standardUserDefaults] setObject:nil forKey:kQuerykey];[[LCBluetoothManager sharedManager] cancelPeripheralConnection];}else{[CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {NSLog(@"%@",error);[CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];}];}//查询用户是否有未结束的租用- (void)getRent{NSString *url = [kBaseUrl stringByAppendingPathComponent:kGetRent];NSString *SIGN = [CommonUtils getSign];NSString *AUTH = [Account shareAccount].user.auth;AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];[manager POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {NSLog(@"%@",responseObject);NSString *status = responseObject[@"status"];NSString *msg = responseObject[@"msg"];if ([status integerValue] == 1) {//更新userView[self updateUserView:responseObject[@"data"]];//锁信息赋给 LCBlueToothMnager;LCBluetoothManager *BTEManager = [LCBluetoothManager sharedManager];if (BTEManager.lockno == nil) {BTEManager.lockno = responseObject[@"data"][@"lockno"];BTEManager.rentid = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"id"]];}//判断蓝牙是否处于连接状态if (BTEManager.conectedState != ConnectedState) {BTEManager.isReconnected = YES;BTEManager.rentid = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"id"]];[BTEManager connectBTEWtihLockNo:responseObject[@"data"][@"lockno"]];}if (_rentTimer == nil) {_rentTimer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(invaliTimer) userInfo:nil repeats:YES];}}else{_useViewHeight.constant = 0;_useView.hidden = YES;;[_rentTimer invalidate];_rentTimer = nil;// [[LocationManager sharedLocationManager] stopSaveRote];}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {NSLog(@"%@",error);}];}- (void)invaliTimer{[self getRent];}//获取用户最新信息- (void)requestMemberInfo{NSString *url = [kBaseUrl stringByAppendingPathComponent:kGetInfo];NSString *SIGN = [CommonUtils getSign];NSString *AUTH = [Account shareAccount].user.auth;AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];[manager POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {NSLog(@"%@",responseObject);[CommonUtils hideHudForView:self.view];NSString *status = responseObject[@"status"];NSString *msg = responseObject[@"msg"];// [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];if ([status integerValue] == 1) {[[Account shareAccount] saveUserInfo:responseObject[@"data"]];}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {NSLog(@"%@",error);[CommonUtils hideHudForView:self.view];[CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];}];}//旧令牌获取新令牌- (void)getAuth{NSString *url = [kBaseUrl stringByAppendingPathComponent:kGetAuth];NSString *SIGN = [CommonUtils getSign];NSString *AUTH = [Account shareAccount].user.auth;NSString *IMEI = [CommonUtils getDeviceUUID];AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {//参数[formData appendPartWithFormData:[IMEI dataUsingEncoding:NSUTF8StringEncoding] name:@"IMEI"];[formData appendPartWithFormData:[@"2" dataUsingEncoding:NSUTF8StringEncoding] name:@"client"];} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {[CommonUtils hideHudForView:self.view];NSLog(@"%@",responseObject);NSString *status = responseObject[@"status"];NSString *msg = responseObject[@"msg"];if ([status integerValue] == 1) {//验证成功,保存用户数据,// [[Account shareAccount] saveUserInfo:responseObject[@"data"]];}else{[CommonUtils showTextHudModeWithInfo:@"登录过期,请重新登录" view:self.view stayTime:1.5];[[Account shareAccount] logout];}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {NSLog(@"%@",error);}];}//获取商圈- (void)getBusinessArea{NSString *url = [kBaseUrl stringByAppendingPathComponent:kGetBusinessArea];NSString *SIGN = [CommonUtils getSign];AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {NSString *city = [LocationManager sharedLocationManager].loctionInfo.city;if (city == nil) {[formData appendPartWithFormData:[@"武汉市" dataUsingEncoding:NSUTF8StringEncoding] name:@"cityName"];}else{[formData appendPartWithFormData:[city dataUsingEncoding:NSUTF8StringEncoding] name:@"cityName"];}} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {NSLog(@"%@",responseObject);NSString *status = responseObject[@"status"];NSString *msg = responseObject[@"msg"];if ([status integerValue] == 1) {//保存商圈数据_areaArr = [NSMutableArray array];for (NSDictionary *dict in responseObject[@"data"]) {BusinessArea *area = [[BusinessArea alloc] initBusinessArea:dict];[_areaArr addObject:area];//创建围栏double latitude = [dict[@"latitude"] doubleValue];double longitude = [dict[@"longitude"] doubleValue];double radius = [dict[@"radius"] doubleValue];NSString *areaId = dict[@"id"];CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);[self.geoFenceManager addCircleRegionForMonitoringWithCenter:coordinate radius:radius customID:areaId];//构造圆MACircle *circle = [MACircle circleWithCenterCoordinate:coordinate radius:radius];//在地图上添加圆[_mapView addOverlay: circle];}}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {NSLog(@"%@",error);}];}#pragma mark - 懒加载#pragma mark - private- (IBAction)message:(UIButton *)sender {MessageTableViewController *vc = [[MessageTableViewController alloc] init];[self.navigationController pushViewController:vc animated:YES];}//关锁未结算计费- (IBAction)repair:(UIButton *)sender {[[LCBluetoothManager sharedManager] cancelPeripheralConnection];[[LocationManager sharedLocationManager] stopSaveRoute];NSString *url = [kBaseUrl stringByAppendingPathComponent:kRepair];[CommonUtils sendPOST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {//参数 必选://锁编号[formData appendPartWithFormData:[[LCBluetoothManager sharedManager].lockno dataUsingEncoding:NSUTF8StringEncoding] name:@"lockId"];// 报修类型[formData appendPartWithFormData:[@"7" dataUsingEncoding:NSUTF8StringEncoding] name:@"repairId"];// 故障类型[formData appendPartWithFormData:[@"关锁未结算" dataUsingEncoding:NSUTF8StringEncoding] name:@"faultName"];// 归还地点NSString *returnposition = [NSString stringWithFormat:@"%f,%f",[LocationManager sharedLocationManager].latitude,[LocationManager sharedLocationManager].longitude];[formData appendPartWithFormData:[returnposition dataUsingEncoding:NSUTF8StringEncoding] name:@"returnposition"];//租赁id[formData appendPartWithFormData:[[LCBluetoothManager sharedManager].rentid dataUsingEncoding:NSUTF8StringEncoding] name:@"rentId"];[formData appendPartWithFormData:[@"" dataUsingEncoding:NSUTF8StringEncoding] name:@"problemDescription"];[formData appendPartWithFormData:[@"" dataUsingEncoding:NSUTF8StringEncoding] name:@"url"];} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {NSLog(@"%@",responseObject);NSString *status = responseObject[@"status"];NSString *msg = responseObject[@"msg"];if ([status integerValue] == 1) {[self skipFee:responseObject[@"data"]];[[NSUserDefaults standardUserDefaults] setObject:nil forKey:kQuerykey];}else{[CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {NSLog(@"%@",error);[CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];}];}//点击缴纳押金- (void)skipDeposit{if (![[Account shareAccount] isLogin]) {//跳转登录页面[self skipLogin];}else{//判断是否实名认证if ([[Account shareAccount].user.verified integerValue] == 0) {//跳转实名认证UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Login" bundle:[NSBundle mainBundle]];AuthViewController *vc = [sb instantiateViewControllerWithIdentifier:@"auth"];[self.navigationController pushViewController:vc animated:YES];}else{//跳转缴纳押金[self skipRechargeDeposit];}}}- (void)skipLogin{UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Login" bundle:[NSBundle mainBundle]];LoginViewController *loginVc = [sb instantiateViewControllerWithIdentifier:@"login"];[self.navigationController pushViewController:loginVc animated:YES];}- (void)skipRechargeDeposit{UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Login" bundle:[NSBundle mainBundle]];DepositViewController *vc = [sb instantiateViewControllerWithIdentifier:@"deposit"];[self.navigationController pushViewController:vc animated:YES];}/**回到地图当前位置*/- (IBAction)setCurrent:(UIButton *)sender {if (![[Account shareAccount] isLogin]) {//跳转登录页面[self skipLogin];}else{_mapView.centerCoordinate = _mapView.userLocation.location.coordinate;}}/**弹出信息反馈页面@param sender nil*/- (IBAction)setting:(UIButton *)sender {if (![[Account shareAccount] isLogin]) {//跳转登录页面[self skipLogin];}else{_settingView.hidden = NO;[self.view bringSubviewToFront:_settingView];// UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];//// WebViewController *vc = [[WebViewController alloc] init];// vc.url = @"http://manage.mabaoxc.com/html/problems.html";// [self.navigationController pushViewController:vc animated:YES];}}/**跳转个人中心@param sender nil*/- (IBAction)skipUser:(UIButton *)sender {if (![[Account shareAccount] isLogin]) {//跳转登录页面[self skipLogin];}else{UIStoryboard *sb = [UIStoryboard storyboardWithName:@"User" bundle:[NSBundle mainBundle]];UserTableViewController *userVC = [sb instantiateViewControllerWithIdentifier:@"user"];[self.navigationController pushViewController:userVC animated:YES];}}/**刷新地图@param sender nil*/- (IBAction)refreshMap:(UIButton *)sender {[_mapView reloadMap];}//扫码- (IBAction)scan:(UIButton *)sender {if (![[Account shareAccount] isLogin]) {//跳转登录页面[self skipLogin];}else if ([[Account shareAccount].user.hasdeposit floatValue] == 0){//未交押金 跳转缴纳押金页面[self skipDeposit];}else if ([[Account shareAccount].user.money floatValue] <0){//跳转充值页面UIStoryboard *sb = [UIStoryboard storyboardWithName:@"User" bundle:[NSBundle mainBundle]];WalletViewController *vc = [sb instantiateViewControllerWithIdentifier:@"wallet"];[self.navigationController pushViewController:vc animated:YES];}// else if (![LCBluetoothManager isBlueOpen]){// //蓝牙未打开 提示用户开启蓝牙// [CommonUtils showAlertWithTitle:@"系统提示" alertMessage:@"检测您的蓝牙设备未开启,需要打开蓝牙才能扫码骑车" action1Title:@"去打开蓝牙" action1Stytle:UIAlertActionStyleDefault action1Handler:^(UIAlertAction *action) {// [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Bluetooth"]];// } action2Title:@"取消" action1Stytle:UIAlertActionStyleCancel action1Handler:^(UIAlertAction *action) {//// } presentVC:self];// }else{ScanViewController *vc = [[ScanViewController alloc] init];vc.style = [StyleDIY myStyle];vc.isOpenInterestRect = YES;vc.libraryType = SLT_Native;vc.scanCodeType = SCT_QRCode;[self.navigationController pushViewController:vc animated:YES];}}#pragma mark - SettingViewDelegate-(void)didSelectedService1{UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];Service1ViewController *vc1 = [sb instantiateViewControllerWithIdentifier:@"service1"];[self.navigationController pushViewController:vc1 animated:YES];}-(void)didSelectedService2{UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];Service2ViewController *vc2 = [sb instantiateViewControllerWithIdentifier:@"service2"];[self.navigationController pushViewController:vc2 animated:YES];}-(void)didSelectedService3{UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];Service3ViewController *vc3 = [sb instantiateViewControllerWithIdentifier:@"service3"];[self.navigationController pushViewController:vc3 animated:YES];}-(void)didSelectedService4{UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];Service4ViewController *vc3 = [sb instantiateViewControllerWithIdentifier:@"service4"];[self.navigationController pushViewController:vc3 animated:YES];}#pragma mark - MapDelegate//用户地理位置更新的时候-(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{if (!updatingLocation && self.userLocationAnnotationView != nil){[UIView animateWithDuration:0.1 animations:^{double degree = userLocation.heading.trueHeading - self.mapView.rotationDegree;self.userLocationAnnotationView.transform = CGAffineTransformMakeRotation(degree * M_PI / 180.f );}];}//记录轨迹}//地图的显示区域已经发生改变的时候调用- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction{if (wasUserAction) {[UIView animateWithDuration:0.5 animations:^{_locationImage.center = CGPointMake(self.view.center.x, self.view.center.y-20);} completion:^(BOOL finished) {_locationImage.center = CGPointMake(self.view.center.x, self.view.center.y);}];}}- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated{;}//地图上绘制圆-(MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay{if ([overlay isKindOfClass:[MACircle class]]){MACircleRenderer *circleRenderer = [[MACircleRenderer alloc] initWithCircle:overlay];circleRenderer.lineWidth = 1.f;circleRenderer.strokeColor = [UIColor colorWithRed:126.f/255.f green:209.f/255.f blue:236.f/255.f alpha:0.4];circleRenderer.fillColor = [UIColor colorWithRed:126.f/255.f green:209.f/255.f blue:236.f/255.f alpha:0.4];return circleRenderer;}/* 自定义定位精度对应的MACircleView. */if (overlay == mapView.userLocationAccuracyCircle){MACircleRenderer *accuracyCircleRenderer = [[MACircleRenderer alloc] initWithCircle:overlay];accuracyCircleRenderer.lineWidth = 2.f;accuracyCircleRenderer.strokeColor = [UIColor lightGrayColor];accuracyCircleRenderer.fillColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:.3];return accuracyCircleRenderer;}return nil;}//地理围栏- (void)amapGeoFenceManager:(AMapGeoFenceManager *)manager didAddRegionForMonitoringFinished:(NSArray<AMapGeoFenceRegion *> *)regions customID:(NSString *)customID error:(NSError *)error {if (error) {NSLog(@"创建失败 %@",error);} else {NSLog(@"创建成功");}}- (void)amapGeoFenceManager:(AMapGeoFenceManager *)manager didGeoFencesStatusChangedForRegion:(AMapGeoFenceRegion *)region customID:(NSString *)customID error:(NSError *)error {if (error) {NSLog(@"status changed error %@",error);}else{if (region.fenceStatus == AMapGeoFenceRegionStatusInside) {[self getLocksWithFenceId:customID];}}}//绘制点- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation{if ([annotation isKindOfClass:[MAPointAnnotation class]] && !([annotation isKindOfClass:[MAUserLocation class]])){static NSString *reuseIndetifier = @"annotationReuseIndetifier";MAAnnotationView *annotationView = (MAAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];if (annotationView == nil){annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];}annotationView.imageView.frame = CGRectMake(0, 0, 20, 20);annotationView.image = [UIImage imageNamed:@"logo_icon"];//设置中心点偏移,使得标注底部中间点成为经纬度对应点annotationView.centerOffset = CGPointMake(0, -18);return annotationView;}/* 自定义userLocation对应的annotationView. */if ([annotation isKindOfClass:[MAUserLocation class]]){static NSString *userLocationStyleReuseIndetifier = @"userLocationStyleReuseIndetifier";MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:userLocationStyleReuseIndetifier];if (annotationView == nil){annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotationreuseIdentifier:userLocationStyleReuseIndetifier];}annotationView.image = [UIImage imageNamed:@"userPosition"];self.userLocationAnnotationView = annotationView;return annotationView;}return nil;}#pragma mark - CLLocationManagerDelegate-(void)centralManagerDidUpdateState:(CBCentralManager *)central{//第一次打开或者每次蓝牙状态改变都会调用这个函数if(central.state==CBCentralManagerStatePoweredOn){NSLog(@"蓝牙设备开着");}else{[CommonUtils showTextHudModeWithInfo:@"蓝牙未打开" view:self.view stayTime:1.5];}}- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.}-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{if ([touches allObjects][0].view != _settingView) {_settingView.hidden = YES;_showSettingView = NO;}}
- (void)viewDidLoad {[super viewDidLoad];[self drawColor];}-(void)viewWillAppear:(BOOL)animated{[super viewWillAppear:animated];[self setNav];if (_codeStr) {_code.text = _codeStr;}}- (void)setNav{self.navigationController.navigationBar.hidden = NO;self.title = @"开不了锁";UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];left.image = [UIImage imageNamed:@"back"];left.tintColor = [UIColor blackColor];self.navigationItem.leftBarButtonItem = left;}- (void)drawColor{CAGradientLayer *gradientLayer = [CAGradientLayer layer];UIColor *beginColor = [UIColor colorWithRed:210.f/255.f green:20/255.f blue:25.f/255.f alpha:1];UIColor *endColor = [UIColor colorWithRed:240.f/255.f green:130.f/255.f blue:45.f/255.f alpha:1];gradientLayer.colors = @[(__bridge id)beginColor.CGColor, (__bridge id)endColor.CGColor];gradientLayer.locations = @[@0.1,@1.0];gradientLayer.startPoint = CGPointMake(0, 0);gradientLayer.endPoint = CGPointMake(1.0, 0);gradientLayer.frame = CGRectMake(0, 0, kScreenW, _sureBtn.bounds.size.height);[self.sureBtn.layer addSublayer:gradientLayer];_sureBtn.layer.cornerRadius = _sureBtn.bounds.size.height/2;_sureBtn.clipsToBounds = YES;[_code setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];}- (void)close{[self.navigationController popViewControllerAnimated:YES];}- (IBAction)submit:(UIButton *)sender {[_comment resignFirstResponder];[_code resignFirstResponder];if (_code.text.length<8) {[CommonUtils showTextHudModeWithInfo:@"请输入正确的锁编号" view:self.view stayTime:1.5];}else{[CommonUtils showLoadingHudWithView:self.view text:nil];NSString *url = [kBaseUrl stringByAppendingPathComponent:kRepair];NSString *SIGN = [CommonUtils getSign];NSString *AUTH = [Account shareAccount].user.auth;AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {//参数 必选:[formData appendPartWithFormData:[_code.text dataUsingEncoding:NSUTF8StringEncoding] name:@"lockId"];[formData appendPartWithFormData:[@"1" dataUsingEncoding:NSUTF8StringEncoding] name:@"repairId"];[formData appendPartWithFormData:[@"开不了锁" dataUsingEncoding:NSUTF8StringEncoding] name:@"faultName"];//可选:[formData appendPartWithFormData:[_comment.text dataUsingEncoding:NSUTF8StringEncoding] name:@"problemDescription"];LocationManager *manager = [LocationManager sharedLocationManager];NSString *returnposition = [NSString stringWithFormat:@"%f,%f",manager.latitude,manager.longitude];[formData appendPartWithFormData:[returnposition dataUsingEncoding:NSUTF8StringEncoding] name:@"returnposition"];} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {[CommonUtils hideHudForView:self.view];NSLog(@"%@",responseObject);NSString *status = responseObject[@"status"];NSString *msg = responseObject[@"msg"];[CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {NSLog(@"%@",error);[CommonUtils hideHudForView:self.view];[CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];}];}}- (IBAction)scan:(UIButton *)sender {ScanViewController *vc = [[ScanViewController alloc] init];vc.style = [StyleDIY myStyle];vc.isOpenInterestRect = YES;vc.libraryType = SLT_Native;vc.scanCodeType = SCT_QRCode;vc.isInputCode = YES;[self.navigationController pushViewController:vc animated:YES];}-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{[_comment resignFirstResponder];[_code resignFirstResponder];}- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.}
- (void)viewDidLoad {[super viewDidLoad];_selectImage.userInteractionEnabled = YES;UITapGestureRecognizer *tapGestureRecognizer1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selecteImage)];[self.selectImage addGestureRecognizer:tapGestureRecognizer1];_allQuestion = @[@"车太重,骑不动",@"二维码脱落",@"把套坏了",@"车铃丢了",@"踏板坏了",@"龙头歪斜",@"刹车失灵",@"其他"];_selectedQuestion = [NSMutableArray array];_selectIndexArr = [NSMutableArray array];[self drawColor];}-(void)viewDidAppear:(BOOL)animated{[super viewDidAppear:animated];_pickerVc = [[UIImagePickerController alloc] init];_pickerVc.delegate = self;_pickerVc.allowsEditing = YES;}-(void)viewWillAppear:(BOOL)animated{[super viewWillAppear:animated];[self setUpNav];if (_codeStr) {_code.text = _codeStr;}}- (void)setUpNav{self.navigationController.navigationBar.hidden = NO;self.title = @"故障上报";UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];left.image = [UIImage imageNamed:@"back"];left.tintColor = [UIColor blackColor];self.navigationItem.leftBarButtonItem = left;}- (void)close{[self.navigationController popViewControllerAnimated:YES];}- (void)drawColor{CAGradientLayer *gradientLayer = [CAGradientLayer layer];UIColor *beginColor = [UIColor colorWithRed:210.f/255.f green:20/255.f blue:25.f/255.f alpha:1];UIColor *endColor = [UIColor colorWithRed:240.f/255.f green:130.f/255.f blue:45.f/255.f alpha:1];gradientLayer.colors = @[(__bridge id)beginColor.CGColor, (__bridge id)endColor.CGColor];gradientLayer.locations = @[@0.1,@1.0];gradientLayer.startPoint = CGPointMake(0, 0);gradientLayer.endPoint = CGPointMake(1.0, 0);gradientLayer.frame = CGRectMake(0, 0, kScreenW, _sureBtn.bounds.size.height);[self.sureBtn.layer addSublayer:gradientLayer];_sureBtn.layer.cornerRadius = _sureBtn.bounds.size.height/2;_sureBtn.clipsToBounds = YES;[_code setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];}- (IBAction)scan:(UIButton *)sender {ScanViewController *vc = [[ScanViewController alloc] init];vc.style = [StyleDIY myStyle];vc.isOpenInterestRect = YES;vc.libraryType = SLT_Native;vc.scanCodeType = SCT_QRCode;vc.isInputCode = YES;[self.navigationController pushViewController:vc animated:YES];}- (IBAction)clickQuestion:(UIButton *)sender {NSString *tagStr = [NSString stringWithFormat:@"%ld",(long)sender.tag];if ([_selectIndexArr containsObject:tagStr]) {[sender setImage:[UIImage imageNamed:@"ic_unselet"] forState:UIControlStateNormal];[_selectIndexArr removeObject:tagStr];[_selectedQuestion removeObject:_allQuestion[sender.tag-100]];}else{[sender setImage:[UIImage imageNamed:@"ic_selected1"] forState:UIControlStateNormal];[_selectIndexArr addObject:tagStr];[_selectedQuestion addObject:_allQuestion[sender.tag-100]];}NSLog(@"%@",[_selectedQuestion componentsJoinedByString:@","]);}- (void)selecteImage{UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {_pickerVc.sourceType = UIImagePickerControllerSourceTypeCamera;[self presentViewController:_pickerVc animated:YES completion:nil];}];[alertVC addAction:cameraAction];UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {_pickerVc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;[self presentViewController:_pickerVc animated:YES completion:nil];}];[alertVC addAction:albumAction];UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {}];[alertVC addAction:cancleAction];[self presentViewController:alertVC animated:YES completion:nil];}- (IBAction)submit:(UIButton *)sender {[_comment resignFirstResponder];[_code resignFirstResponder];if (_code.text.length<8) {[CommonUtils showTextHudModeWithInfo:@"请输入正确的锁编号" view:self.view stayTime:1.5];}else if (_selectedQuestion.count == 0){[CommonUtils showTextHudModeWithInfo:@"请至少选择一个故障原因" view:self.view stayTime:1.5];}else{[CommonUtils showLoadingHudWithView:self.view text:nil];NSString *url = [kBaseUrl stringByAppendingPathComponent:kRepair];NSString *SIGN = [CommonUtils getSign];NSString *AUTH = [Account shareAccount].user.auth;AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {//参数[formData appendPartWithFormData:[_code.text dataUsingEncoding:NSUTF8StringEncoding] name:@"lockId"];[formData appendPartWithFormData:[@"2" dataUsingEncoding:NSUTF8StringEncoding] name:@"repairId"];[formData appendPartWithFormData:[[_selectedQuestion componentsJoinedByString:@","] dataUsingEncoding:NSUTF8StringEncoding] name:@"faultName"];[formData appendPartWithFormData:[_comment.text dataUsingEncoding:NSUTF8StringEncoding] name:@"problemDescription"];if (_image) {[formData appendPartWithFormData:UIImageJPEGRepresentation(_image, 0.2) name:@"url"];}LocationManager *manager = [LocationManager sharedLocationManager];NSString *returnposition = [NSString stringWithFormat:@"%f,%f",manager.latitude,manager.longitude];[formData appendPartWithFormData:[returnposition dataUsingEncoding:NSUTF8StringEncoding] name:@"returnposition"];} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {[CommonUtils hideHudForView:self.view];NSLog(@"%@",responseObject);NSString *msg = responseObject[@"msg"];[CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {NSLog(@"%@",error);[CommonUtils hideHudForView:self.view];[CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];}];}}-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{[_comment resignFirstResponder];[_code resignFirstResponder];}- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{NSLog(@"%@",info);_selectImage.image = info[@"UIImagePickerControllerEditedImage"];_image = info[@"UIImagePickerControllerEditedImage"];[self dismissViewControllerAnimated:YES completion:nil];}- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{[self dismissViewControllerAnimated:YES completion:nil];}
#import "Service3ViewController.h"#import "CommonUtils.h"#import "Account.h"#import "ScanViewController.h"#import "StyleDIY.h"#import "Home.h"#import "LocationManager.h"@interface Service3ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>@property (weak, nonatomic) IBOutlet UIImageView *selectImage;@property (weak, nonatomic) IBOutlet UITextField *code;@property (weak, nonatomic) IBOutlet UITextView *comment;@property (nonatomic,strong) UIImagePickerController *pickerVc;@property (nonatomic,strong) UIImage *image;@property (weak, nonatomic) IBOutlet UIButton *sureBtn;@end@implementation Service3ViewController- (void)viewDidLoad {[super viewDidLoad];_selectImage.userInteractionEnabled = YES;UITapGestureRecognizer *tapGestureRecognizer1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selecteImage)];[self.selectImage addGestureRecognizer:tapGestureRecognizer1];[self drawColor];}-(void)viewDidAppear:(BOOL)animated{[super viewDidAppear:animated];_pickerVc = [[UIImagePickerController alloc] init];_pickerVc.delegate = self;_pickerVc.allowsEditing = YES;}- (void)viewWillAppear:(BOOL)animated{[super viewWillAppear:animated];[self setUpNav];if (_codeStr) {_code.text = _codeStr;}}- (void)drawColor{CAGradientLayer *gradientLayer = [CAGradientLayer layer];UIColor *beginColor = [UIColor colorWithRed:210.f/255.f green:20/255.f blue:25.f/255.f alpha:1];UIColor *endColor = [UIColor colorWithRed:240.f/255.f green:130.f/255.f blue:45.f/255.f alpha:1];gradientLayer.colors = @[(__bridge id)beginColor.CGColor, (__bridge id)endColor.CGColor];gradientLayer.locations = @[@0.1,@1.0];gradientLayer.startPoint = CGPointMake(0, 0);gradientLayer.endPoint = CGPointMake(1.0, 0);gradientLayer.frame = CGRectMake(0, 0, kScreenW, _sureBtn.bounds.size.height);[self.sureBtn.layer addSublayer:gradientLayer];_sureBtn.layer.cornerRadius = _sureBtn.bounds.size.height/2;_sureBtn.clipsToBounds = YES;[_code setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];}- (void)setUpNav{self.navigationController.navigationBar.hidden = NO;self.title = @"举报违停";UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];left.image = [UIImage imageNamed:@"back"];left.tintColor = [UIColor blackColor];self.navigationItem.leftBarButtonItem = left;}- (void)close{[self.navigationController popViewControllerAnimated:YES];}- (IBAction)submit:(UIButton *)sender {[_comment resignFirstResponder];[_code resignFirstResponder];if (_code.text.length<8) {[CommonUtils showTextHudModeWithInfo:@"请输入正确的锁编号" view:self.view stayTime:1.5];}else{[CommonUtils showLoadingHudWithView:self.view text:nil];NSString *url = [kBaseUrl stringByAppendingPathComponent:kRepair];NSString *SIGN = [CommonUtils getSign];NSString *AUTH = [Account shareAccount].user.auth;AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {//参数[formData appendPartWithFormData:[_code.text dataUsingEncoding:NSUTF8StringEncoding] name:@"lockId"];[formData appendPartWithFormData:[@"3" dataUsingEncoding:NSUTF8StringEncoding] name:@"repairId"];[formData appendPartWithFormData:[@"举报违停" dataUsingEncoding:NSUTF8StringEncoding] name:@"faultName"];[formData appendPartWithFormData:[_comment.text dataUsingEncoding:NSUTF8StringEncoding] name:@"problemDescription"];LocationManager *manager = [LocationManager sharedLocationManager];NSString *returnposition = [NSString stringWithFormat:@"%f,%f",manager.latitude,manager.longitude];[formData appendPartWithFormData:[returnposition dataUsingEncoding:NSUTF8StringEncoding] name:@"returnposition"];} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {[CommonUtils hideHudForView:self.view];NSLog(@"%@",responseObject);NSString *status = responseObject[@"status"];NSString *msg = responseObject[@"msg"];[CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {NSLog(@"%@",error);[CommonUtils hideHudForView:self.view];[CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];}];}}- (IBAction)scan:(UIButton *)sender {ScanViewController *vc = [[ScanViewController alloc] init];vc.style = [StyleDIY myStyle];vc.isOpenInterestRect = YES;vc.libraryType = SLT_Native;vc.scanCodeType = SCT_QRCode;vc.isInputCode = YES;[self.navigationController pushViewController:vc animated:YES];}- (void)selecteImage{// _pickerVc = [[UIImagePickerController alloc] init];// _pickerVc.delegate = self;// _pickerVc.allowsEditing = YES;UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {_pickerVc.sourceType = UIImagePickerControllerSourceTypeCamera;[self presentViewController:_pickerVc animated:YES completion:nil];}];[alertVC addAction:cameraAction];UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {_pickerVc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;[self presentViewController:_pickerVc animated:YES completion:nil];}];[alertVC addAction:albumAction];UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {}];[alertVC addAction:cancleAction];[self presentViewController:alertVC animated:YES completion:nil];}-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{[_comment resignFirstResponder];[_code resignFirstResponder];}- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{_selectImage.image = info[@"UIImagePickerControllerEditedImage"];_image = info[@"UIImagePickerControllerEditedImage"];[self dismissViewControllerAnimated:YES completion:nil];}- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.}
#import "Service4ViewController.h"#import "CommonUtils.h"#import "Account.h"#import "ScanViewController.h"#import "StyleDIY.h"#import "Home.h"#import "LocationManager.h"@interface Service4ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>@property (weak, nonatomic) IBOutlet UIImageView *selectImage;@property (weak, nonatomic) IBOutlet UITextField *code;@property (nonatomic,strong) UIImagePickerController *pickerVc;@property (weak, nonatomic) IBOutlet UITextView *comment;@property (nonatomic,strong) UIImage *image;@property (weak, nonatomic) IBOutlet UIButton *sureBtn;@end@implementation Service4ViewController- (void)viewDidLoad {[super viewDidLoad];_selectImage.userInteractionEnabled = YES;UITapGestureRecognizer *tapGestureRecognizer1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selecteImage)];[self.selectImage addGestureRecognizer:tapGestureRecognizer1];[self drawColor];}-(void)viewDidAppear:(BOOL)animated{[super viewDidAppear:animated];_pickerVc = [[UIImagePickerController alloc] init];_pickerVc.delegate = self;_pickerVc.allowsEditing = YES;}- (void)viewWillAppear:(BOOL)animated{[super viewWillAppear:animated];[self setUpNav];if (_codeStr) {_code.text = _codeStr;}}- (void)drawColor{CAGradientLayer *gradientLayer = [CAGradientLayer layer];UIColor *beginColor = [UIColor colorWithRed:210.f/255.f green:20/255.f blue:25.f/255.f alpha:1];UIColor *endColor = [UIColor colorWithRed:240.f/255.f green:130.f/255.f blue:45.f/255.f alpha:1];gradientLayer.colors = @[(__bridge id)beginColor.CGColor, (__bridge id)endColor.CGColor];gradientLayer.locations = @[@0.1,@1.0];gradientLayer.startPoint = CGPointMake(0, 0);gradientLayer.endPoint = CGPointMake(1.0, 0);gradientLayer.frame = CGRectMake(0, 0, kScreenW, _sureBtn.bounds.size.height);[self.sureBtn.layer addSublayer:gradientLayer];_sureBtn.layer.cornerRadius = _sureBtn.bounds.size.height/2;_sureBtn.clipsToBounds = YES;[_code setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];}- (void)setUpNav{self.navigationController.navigationBar.hidden = NO;self.title = @"清洁维护";UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];left.image = [UIImage imageNamed:@"back"];left.tintColor = [UIColor blackColor];self.navigationItem.leftBarButtonItem = left;}- (void)close{[self.navigationController popViewControllerAnimated:YES];}- (void)selecteImage{UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {_pickerVc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;[self presentViewController:_pickerVc animated:YES completion:nil];}];[alertVC addAction:cameraAction];UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {_pickerVc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;[self presentViewController:_pickerVc animated:YES completion:nil];}];[alertVC addAction:albumAction];UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {}];[alertVC addAction:cancleAction];[self presentViewController:alertVC animated:YES completion:nil];}- (IBAction)scan:(UIButton *)sender {ScanViewController *vc = [[ScanViewController alloc] init];vc.style = [StyleDIY myStyle];vc.isOpenInterestRect = YES;vc.libraryType = SLT_Native;vc.scanCodeType = SCT_QRCode;vc.isInputCode = YES;[self.navigationController pushViewController:vc animated:YES];}- (IBAction)submit:(id)sender {[_comment resignFirstResponder];[_code resignFirstResponder];if (_code.text.length<8) {[CommonUtils showTextHudModeWithInfo:@"请输入正确的锁编号" view:self.view stayTime:1.5];}else{[CommonUtils showLoadingHudWithView:self.view text:nil];NSString *url = [kBaseUrl stringByAppendingPathComponent:kRepair];NSString *SIGN = [CommonUtils getSign];NSString *AUTH = [Account shareAccount].user.auth;AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {//参数[formData appendPartWithFormData:[_code.text dataUsingEncoding:NSUTF8StringEncoding] name:@"lockId"];[formData appendPartWithFormData:[@"4" dataUsingEncoding:NSUTF8StringEncoding] name:@"repairId"];[formData appendPartWithFormData:[@"清洁维护" dataUsingEncoding:NSUTF8StringEncoding] name:@"faultName"];[formData appendPartWithFormData:[_comment.text dataUsingEncoding:NSUTF8StringEncoding] name:@"problemDescription"];LocationManager *manager = [LocationManager sharedLocationManager];NSString *returnposition = [NSString stringWithFormat:@"%f,%f",manager.latitude,manager.longitude];[formData appendPartWithFormData:[returnposition dataUsingEncoding:NSUTF8StringEncoding] name:@"returnposition"];} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {[CommonUtils hideHudForView:self.view];NSLog(@"%@",responseObject);NSString *msg = responseObject[@"msg"];[CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {NSLog(@"%@",error);[CommonUtils hideHudForView:self.view];[CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];}];}}- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{_selectImage.image = info[@"UIImagePickerControllerEditedImage"];_image = info[@"UIImagePickerControllerEditedImage"];[self dismissViewControllerAnimated:YES completion:nil];}-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{[_comment resignFirstResponder];[_code resignFirstResponder];}
#import "ScanViewController.h"#import "ScanBottomView.h"#import "InputCodeViewController.h"#import <CoreBluetooth/CoreBluetooth.h>#import "Home.h"#import "CommonUtils.h"#import "Account.h"#import "LCBluetoothManager.h"@interface ScanViewController ()@property (nonatomic,strong) ScanBottomView *bottomView;@property (nonatomic,strong) UILabel *tiplabel;@property (nonatomic,strong) UIButton *closeBtn;@property (nonatomic,strong) CBCentralManager *centralManager;@property (nonatomic,strong) CBPeripheralManager *peripheralManager;@property (nonatomic,strong) CBPeripheral *peripheral;@property (nonatomic,strong) NSString *secretkey;@property (nonatomic,strong) CBCharacteristic *characteristic;@property (nonatomic,strong) NSString *lockNo;@property (nonatomic) BOOL isBluetoothOpen;@end#define SERVICES_UUID @"1960"#define WRITE_UUID @"2BB1"#define READ_UUID @"2BB2"@implementation ScanViewController- (void)viewDidLoad {[super viewDidLoad];if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {self.edgesForExtendedLayout = UIRectEdgeNone;}self.view.backgroundColor = [UIColor blackColor];self.navigationController.navigationBar.hidden = YES;//注册通知[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(openSuccess) name:kOpenLockSuccess object:nil];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(openFailed) name:kOpenLockFailed object:nil];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopScan) name:kStopScap object:nil];_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];}-(void)openSuccess{[CommonUtils hideHudForView:self.view];[self.navigationController popViewControllerAnimated:YES];}-(void)openFailed{[CommonUtils hideHudForView:self.view];[CommonUtils showTextHudModeWithInfo:@"开锁失败" view:self.view stayTime:1.5];[self reStartDevice];}- (void)stopScan{[CommonUtils hideHudForView:self.view];// [CommonUtils showTextHudModeWithInfo:@"扫描不到可用的蓝牙信息" view:self.view stayTime:1.5];[self reStartDevice];}-(void)viewWillAppear:(BOOL)animated{[super viewWillAppear:animated];self.navigationController.navigationBar.hidden = YES;if (_codeStr) {//手动输入编码,连接蓝牙;[self requestOpenLock:_codeStr];}}-(void)viewDidAppear:(BOOL)animated{[super viewDidAppear:animated];[self setUpScanView];}- (void)closePage{[self.navigationController popViewControllerAnimated:YES];}- (void)setUpScanView{//底部视图if (!_bottomView ) {_bottomView = [[NSBundle mainBundle] loadNibNamed:@"ScanBottomView" owner:nil options:nil][0];[self.view addSubview:_bottomView];_bottomView.frame = CGRectMake(0, CGRectGetMaxY(self.view.frame)-120, CGRectGetWidth(self.view.frame), 100);[self.view bringSubviewToFront:_bottomView];[_bottomView.input addTarget:self action:@selector(inputCode) forControlEvents:UIControlEventTouchUpInside];[_bottomView.flash addTarget:self action:@selector(openFlash) forControlEvents:UIControlEventTouchDown];}//提示文字if (!_tiplabel) {_tiplabel = [[UILabel alloc] init];_tiplabel.bounds = CGRectMake(0, 0, 145, 60);_tiplabel.center = CGPointMake(CGRectGetWidth(self.view.frame)/2, 100);_tiplabel.textAlignment = NSTextAlignmentCenter;_tiplabel.numberOfLines = 0;_tiplabel.font = [UIFont systemFontOfSize:15];_tiplabel.text = @"将取景框对准二维码即可自动扫描";_tiplabel.textColor = [UIColor whiteColor];[self.view addSubview:_tiplabel];}//返回按钮if (!_closeBtn) {_closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];[_closeBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];_closeBtn.frame = CGRectMake(0, 16, 60, 60);[_closeBtn addTarget:self action:@selector(closePage) forControlEvents:UIControlEventTouchUpInside];// _closeBtn.tintColor = [UIColor redColor];//// _closeB[self.view addSubview:_closeBtn];[self.view bringSubviewToFront:_closeBtn];}}- (void)inputCode{UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];InputCodeViewController *vc = [sb instantiateViewControllerWithIdentifier:@"InputCodeVc"];vc.isInputCode = _isInputCode;[self.navigationController pushViewController:vc animated:YES];}- (void)openFlash{[self openOrCloseFlash];if (self.isOpenFlash) {[_bottomView.flash setImage:[UIImage imageNamed:@"手电筒2"] forState:UIControlStateNormal];}else{[_bottomView.flash setImage:[UIImage imageNamed:@"手电筒"] forState:UIControlStateNormal];}}- (void)scanResultWithArray:(NSArray<LBXScanResult*>*)array{if (!array || array.count < 1)//二维码的内容格式: http://locks.mabaoxc.com?lockno=72000049{return;}NSString *temStr = array[0].strScanned;if ([temStr hasPrefix:@"http://locks.mabaoxc.com?lockno"]) {NSString *code = [temStr componentsSeparatedByString:@"="].lastObject;_lockNo = code;if (_isInputCode) {NSArray *vcArr = self.navigationController.viewControllers;UIViewController *vc = vcArr[vcArr.count-2];[vc setValue:code forKey:@"codeStr"];[self.navigationController popViewControllerAnimated:YES];}else{if (_isBluetoothOpen) {[self requestOpenLock:code];}else{[CommonUtils showTextHudModeWithInfo:@"请打开蓝牙" view:self.view stayTime:1.5];}}}else{UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"提示" message:temStr preferredStyle:UIAlertControllerStyleAlert];UIAlertAction *act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];[vc addAction:act];[self presentViewController:vc animated:YES completion:nil];}}#pragma mark - 网络请求- (void)requestOpenLock:(NSString *)str{[CommonUtils showLoadingHudWithView:self.view text:@"正在开锁中..."];NSString *url = [kBaseUrl stringByAppendingPathComponent:kOpenLock];NSString *SIGN = [CommonUtils getSign];NSString *AUTH = [Account shareAccount].user.auth;AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {//@"72000049"[formData appendPartWithFormData:[str dataUsingEncoding:NSUTF8StringEncoding] name:@"lockno"];} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {NSLog(@"%@",responseObject);NSString *msg = responseObject[@"msg"];NSString *status = responseObject[@"status"];if ([status integerValue] == 1) {LCBluetoothManager *manager = [LCBluetoothManager sharedManager];[[NSUserDefaults standardUserDefaults] setObject:responseObject[@"data"][@"querykey"] forKey:kQuerykey];manager.secretkey = responseObject[@"data"][@"lockkey"];manager.rentid = responseObject[@"data"][@"rentid"];manager.rentposition = @"30.591498,114.219142";manager.scanView = self.view;manager.lockno = _lockNo;manager.querykey = responseObject[@"data"][@"querykey"];_secretkey = responseObject[@"data"];[manager openLock];}else{[CommonUtils hideHudForView:self.view];[CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];[self reStartDevice];}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {NSLog(@"%@",error);[CommonUtils hideHudForView:self.view];[self reStartDevice];[CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];}];}- (void)centralManagerDidUpdateState:(CBCentralManager *)central{switch (central.state) {case CBCentralManagerStatePoweredOn:{_isBluetoothOpen = YES;[CommonUtils showTextHudModeWithInfo:@"蓝牙功能可用" view:self.view stayTime:1.5];}break;default:_isBluetoothOpen = NO;[CommonUtils showTextHudModeWithInfo:@"蓝牙处于关闭状态" view:self.view stayTime:1.5];break;}}
#import "InputCodeViewController.h"#import "ScanViewController.h"@interface InputCodeViewController ()@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *labels@property (nonatomic) NSUInteger index;@property (nonatomic,strong) NSMutableArray *numArr;@end#define kBordColor [UIColor colorWithRed:208.f/255.f green:18.f/255.f blue:27.f/255.f alpha:1]@implementation InputCodeViewController- (void)viewDidLoad {[super viewDidLoad];self.navigationController.navigationBar.hidden = NO;_index = 0;_numArr = [NSMutableArray array];[self setUpNav];[self setUpLabel];}-(void)viewWillAppear:(BOOL)animated{[super viewWillAppear:animated];self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};}-(void)viewWillDisappear:(BOOL)animated{[super viewWillDisappear:animated];self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor]};}- (void)setUpLabel{for (UILabel *label in _labels) {label.layer.borderColor = [UIColor whiteColor].CGColor;label.layer.borderWidth = 1;}UILabel *firstLabel = _labels[0];firstLabel.layer.borderColor = kBordColor.CGColor;firstLabel.layer.borderWidth = 1;}- (void)setUpNav{self.navigationController.navigationBar.hidden = NO;self.title = @"手动开锁";UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];left.image = [UIImage imageNamed:@"back"];left.tintColor = [UIColor whiteColor];self.navigationItem.leftBarButtonItem = left;[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];[self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];}- (void)close{[self.navigationController popViewControllerAnimated:YES];}- (IBAction)sure:(UIButton *)sender {if (_index<10) {return;}NSString *tem = [_numArr componentsJoinedByString:@","];NSString *codeStr = [tem stringByReplacingOccurrencesOfString:@"," withString:@""];NSArray *VCArr = self.navigationController.viewControllers;if (_isInputCode) {UIViewController *vc = VCArr[VCArr.count-3];[vc setValue:codeStr forKey:@"codeStr"];[self.navigationController popToViewController:vc animated:YES];}else{ScanViewController *vc = VCArr[VCArr.count-2];vc.codeStr = codeStr;[self.navigationController popViewControllerAnimated:YES];}}- (IBAction)clickNumPad:(UIButton *)sender {if (_index<10) {NSInteger num = sender.tag-100;UILabel *codeLabel = _labels[_index];codeLabel.layer.borderColor = [UIColor whiteColor].CGColor;codeLabel.layer.borderWidth = 1;codeLabel.text = [NSString stringWithFormat:@"%ld",(long)num];[_numArr addObject: sender.titleLabel.text];if (_index<9) {UILabel *label = _labels[_index+1];label.layer.borderColor = kBordColor.CGColor;label.layer.borderWidth = 1;}_index++;}}- (IBAction)deleteNum:(UIButton *)sender {if (_index == 0) {return;}[_numArr removeObject:sender.titleLabel.text];UILabel *codeLabel = _labels[_index-1];codeLabel.layer.borderColor = kBordColor.CGColor;codeLabel.layer.borderWidth = 1;codeLabel.text = @"";if (_index<10) {UILabel *label = _labels[_index];label.layer.borderColor = [UIColor whiteColor].CGColor;label.layer.borderWidth = 1;}_index--;}
#import "WebViewController.h"#import <WebKit/WebKit.h>#import "Service1ViewController.h"#import "Service2ViewController.h"#import "Service3ViewController.h"#import "Service4ViewController.h"@interface WebViewController ()<WKUIDelegate,WKNavigationDelegate>@property (nonatomic,strong) WKWebView *webView;@property (nonatomic,strong) NSMutableDictionary *parameterDict;@end@implementation WebViewController- (void)viewDidLoad {[super viewDidLoad];// 配置webView[self setUpWebView];[self setUpNav];}-(void)viewWillAppear:(BOOL)animated{[super viewWillAppear:animated];}-(void)viewWillDisappear:(BOOL)animated{[super viewWillDisappear:animated]}- (void)setUpNav{self.navigationController.navigationBar.hidden = NO;self.title = @"用户指南";UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(close)];left.tintColor = [UIColor blackColor];self.navigationItem.leftBarButtonItem = left;//// self.navigationController.navigationBar.backgroundColor= [UIColor whiteColor];// [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];}- (void)close{if (_webView.backForwardList.backList.count == 0) {[self.navigationController popViewControllerAnimated:YES];}else{[_webView goToBackForwardListItem:_webView.backForwardList.backItem];}}- (void)setUpWebView{self.edgesForExtendedLayout = UIRectEdgeNone;self.automaticallyAdjustsScrollViewInsets = NO;WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];// 设置偏好设置config.preferences = [[WKPreferences alloc] init];// 默认为0config.preferences.minimumFontSize = 12;// 默认认为YESconfig.preferences.javaScriptEnabled = YES;// 在iOS上默认为NO,表示不能自动通过窗口打开config.preferences.javaScriptCanOpenWindowsAutomatically = NO;config.allowsInlineMediaPlayback = YES;// web内容处理池config.processPool = [[WKProcessPool alloc] init];// 通过JS与webview内容交互config.userContentController = [[WKUserContentController alloc] init];// 注入JS对象名称AppModel,当JS通过AppModel来调用时,// 我们可以在WKScriptMessageHandler代理中接收到/Users/reew/Desktop/智橙生活/SHWiseHouse/Classes/Main/Controllers/ViewController.m// [config.userContentController addScriptMessageHandler:self name:@"AppModel"];//// [config.userContentController addScriptMessageHandler:self name:@"tianshan"];self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-64) configuration:config];self.webView.navigationDelegate = self;[self.view addSubview:self.webView];[(UIScrollView *)[[self.webView subviews] objectAtIndex:0] setBounces:NO];self.webView.allowsBackForwardNavigationGestures = NO;// 配置JavascriptBridgeBridgeself.webView.UIDelegate = self;self.webView.scrollView.bounces = NO;// CGFloat phoneVersion = [[[UIDevice currentDevice] systemVersion] floatValue];// if (phoneVersion >= 10.0) {// content = [content stringByReplacingOccurrencesOfString:@"<video" withString:@"<video playsinline"];// }else {// content = [content stringByReplacingOccurrencesOfString:@"<video" withString:@"<video webkit-playsinline"];// }NSURL *url = [NSURL URLWithString:_url];NSURLRequest *request = [NSMutableURLRequest requestWithURL:url];[_webView loadRequest:request];}#pragma mark webview相关- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{NSLog(@"%@",navigationAction.request.URL);NSURL *url = navigationAction.request.URL;NSString *funStr = [[url.absoluteString componentsSeparatedByString:@"="] lastObject];if ([funStr isEqualToString:@"lock"]) {UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];Service1ViewController *vc1 = [sb instantiateViewControllerWithIdentifier:@"service1"];[self.navigationController pushViewController:vc1 animated:YES];decisionHandler(WKNavigationActionPolicyCancel);}else if ([funStr isEqualToString:@"broken"]){UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];Service2ViewController *vc2 = [sb instantiateViewControllerWithIdentifier:@"service2"];[self.navigationController pushViewController:vc2 animated:YES];decisionHandler(WKNavigationActionPolicyCancel);}else if ([funStr isEqualToString:@"reporet"]){UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];Service3ViewController *vc3 = [sb instantiateViewControllerWithIdentifier:@"service3"];[self.navigationController pushViewController:vc3 animated:YES];decisionHandler(WKNavigationActionPolicyCancel);}else if ([funStr isEqualToString:@"others"]){UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];Service4ViewController *vc3 = [sb instantiateViewControllerWithIdentifier:@"service4"];[self.navigationController pushViewController:vc3 animated:YES];decisionHandler(WKNavigationActionPolicyCancel);}else{decisionHandler(WKNavigationActionPolicyAllow);}}
#import "MessageTableViewController.h"#import "Meesage.h"#import "MessageTableViewCell.h"#import <UIImageView+WebCache.h>@interface MessageTableViewController ()@property (nonatomic,strong) NSMutableArray <Meesage *>*messageArr@end@implementation MessageTableViewController- (void)viewDidLoad {[super viewDidLoad];[self setUpTableView];[self requestData];[self setNav];}- (void)setNav{self.navigationController.navigationBar.hidden = NO;self.title = @"消息";UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];left.image = [UIImage imageNamed:@"back"];left.tintColor = [UIColor blackColor];self.navigationItem.leftBarButtonItem = left;self.navigationController.navigationBar.hidden = NO;}- (void)close{[self.navigationController popViewControllerAnimated:YES];}- (void)setUpTableView{self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];[self.tableView registerNib:[UINib nibWithNibName:@"MessageTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"MessageTableViewCell"];self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];}- (void)requestData{[CommonUtils showLoadingHudWithView:self.view text:nil];NSString *url = [kBaseUrl stringByAppendingPathComponent:kGetNewsInfo];[CommonUtils sendNobodyPOST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {[CommonUtils hideHudForView:self.view];NSLog(@"%@",responseObject);NSString *status = responseObject[@"status"];NSString *msg = responseObject[@"msg"];if ([status integerValue] == 1) {_messageArr = [NSMutableArray array];for (NSDictionary *dict in responseObject[@"data"]) {Meesage *message = [[Meesage alloc] initMeesage:dict];[_messageArr addObject:message];}[self.tableView reloadData];}else{[CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {NSLog(@"%@",error);[CommonUtils hideHudForView:self.view];[CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];}];}- (NSString *)getTimeStrWithTimetap:(NSString *)timetamp{NSDateFormatter *stampFormatter = [[NSDateFormatter alloc] init];[stampFormatter setDateFormat:@"YYYY-MM-dd"];//以 1970/01/01 GMT为基准,然后过了secs秒的时间NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timetamp integerValue]/1000];NSString *timeStr = [stampFormatter stringFromDate:date];return timeStr;}#pragma mark - Table view data source- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {return 1;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {return _messageArr.count;}-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{return kScreenW*64/145+70;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MessageTableViewCell" forIndexPath:indexPath];cell.selectionStyle = UITableViewCellSelectionStyleNone;Meesage *news = _messageArr[indexPath.row];[cell.image sd_setImageWithURL:[NSURL URLWithString:news.imgUrl] placeholderImage:nil];cell.newsTitle.text = news.newsTitle;cell.startTime.text = [self getTimeStrWithTimetap:news.starttime];NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间NSTimeInterval time=[date timeIntervalSince1970]*1000;if (time > [news.endtime floatValue]) {cell.usable.hidden = NO;}else{cell.usable.hidden = YES;}return cell;}
#import "LoginViewController.h"#import "CommonUtils.h"#import <MBProgressHUD.h>#import "CommonUtils.h"#import <AFNetworking.h>#import "Login.h"#import "Account.h"#import "AuthViewController.h"#import "WebViewController.h"@interface LoginViewController ()<UITextFieldDelegate>@property (weak, nonatomic) IBOutlet UITextField *phone;@property (weak, nonatomic) IBOutlet UITextField *authCode;@property (weak, nonatomic) IBOutlet UIButton *getAuthCodeBtn;@property (weak, nonatomic) IBOutlet UIButton *sureBtn;@property (weak, nonatomic) IBOutlet UIButton *wxLogin;@endNSTimer *timer;static int timeValue = 60;@implementation LoginViewController- (void)viewDidLoad {[super viewDidLoad];_phone.delegate = self;_authCode.delegate = self;// [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFielddidChangeValue) name:UITextFieldTextDidChangeNotification object:nil];_wxLogin.layer.cornerRadius = 20;_wxLogin.clipsToBounds = YES;_wxLogin.layer.borderColor = [UIColor colorWithRed:116.f/255.f green:197.f/255.f blue:68.f/255.f alpha:1].CGColor;_wxLogin.layer.borderWidth = 0.5;_getAuthCodeBtn.layer.cornerRadius = 15;_getAuthCodeBtn.clipsToBounds = YES;_sureBtn.layer.cornerRadius = 20;_sureBtn.clipsToBounds = YES;}-(void)viewWillAppear:(BOOL)animated{[super viewWillAppear:animated];self.navigationController.navigationBar.hidden = NO;[self setUpNav];}- (void)setUpNav{self.navigationController.navigationBar.hidden = NO;self.title = @"手机验证";UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(closePage)];left.image = [UIImage imageNamed:@"back"];left.tintColor = [UIColor blackColor];self.navigationItem.leftBarButtonItem = left;[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];[self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];}- (void)closePage{[self.navigationController popViewControllerAnimated:YES];}- (void)wxErr{[CommonUtils showTextHudModeWithInfo:@"支付失败" view:self.view stayTime:1.5];}- (IBAction)close:(UIButton *)sender {[self skipHome];}- (IBAction)WXKLogin:(UIButton *)sender {}- (IBAction)SkipAgreement:(UIButton *)sender {WebViewController *vc = [[WebViewController alloc] init];vc.url = @"http://manage.mabaoxc.com/p/notify/getNotify?id=1";[self.navigationController pushViewController:vc animated:YES];}- (void)skipHome{[self.navigationController popToRootViewControllerAnimated:YES];}- (void)dealYzmBut{if (timeValue == 0) {// [_rightView setBackgroundColor:[UIColor colorWithRed:53/255.0 green:163/255.0 blue:223/255.0 alpha:1]];// _getAuthCodeBtn.backgroundColor = [UIColor colorWithRed:51.f/255.f green:51.f/255.f blue:51.f/255.f alpha:1];[_getAuthCodeBtn setTitle:@"获取验证码" forState:0];_getAuthCodeBtn.userInteractionEnabled = YES;timeValue = 60;[timer invalidate];return;}[_getAuthCodeBtn setTitle:[NSString stringWithFormat:@"%ds",timeValue] forState:0];// _getAuthCodeBtn.backgroundColor = [UIColor grayColor];_getAuthCodeBtn.userInteractionEnabled = NO;timeValue--;}- (IBAction)getAuthCode:(UIButton *)sender {if (![CommonUtils isPhoneNum:_phone.text]) {[CommonUtils showTextHudModeWithInfo:@"请输入正确的手机号" view:self.view stayTime:1.5];}else{// timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(dealYzmBut) userInfo:nil repeats:YES];[_phone resignFirstResponder];NSString *IMEI = [CommonUtils getDeviceUUID];NSString *sign = [CommonUtils getSign];AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:sign forHTTPHeaderField:@"SIGN"];NSString *url = [kBaseUrl stringByAppendingPathComponent:kSendsms];[CommonUtils showLoadingHudModelWithView:self.view handle:^{}];[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {[formData appendPartWithFormData:[_phone.text dataUsingEncoding:NSUTF8StringEncoding] name:@"mobile"];[formData appendPartWithFormData:[IMEI dataUsingEncoding:NSUTF8StringEncoding] name:@"IMEI"];} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {NSLog(@"%@",responseObject);NSString *msg = responseObject[@"msg"];NSString *status = responseObject[@"status"];if ([status integerValue] == 1) {timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(dealYzmBut) userInfo:nil repeats:YES];}[CommonUtils hideHudForView:self.view];[CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {NSLog(@"%@",error);[CommonUtils hideHudForView:self.view];[CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];}];}}- (IBAction)login:(UIButton *)sender {// UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Login" bundle:[NSBundle mainBundle]];// AuthViewController *authVC = [sb instantiateViewControllerWithIdentifier:@"auth"];// [self presentViewController:authVC animated:YES completion:nil];//输入信息判断提示if (![CommonUtils isPhoneNum:_phone.text]) {[CommonUtils showTextHudModeWithInfo:@"请输入正确的手机号码" view:self.view stayTime:1];}else if (_authCode.text.length==0){[CommonUtils showTextHudModeWithInfo:@"请输入验证码" view:self.view stayTime:1];}else{//请求登录[CommonUtils showLoadingHudModelWithView:self.view handle:nil];NSString *url = [kBaseUrl stringByAppendingPathComponent:kLogin];NSString *SIGN = [CommonUtils getSign];NSString *IMEI = [CommonUtils getDeviceUUID];AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {//参数[formData appendPartWithFormData:[_phone.text dataUsingEncoding:NSUTF8StringEncoding] name:@"mobile"];[formData appendPartWithFormData:[_authCode.text dataUsingEncoding:NSUTF8StringEncoding] name:@"code"];[formData appendPartWithFormData:[IMEI dataUsingEncoding:NSUTF8StringEncoding] name:@"IMEI"];[formData appendPartWithFormData:[@"2" dataUsingEncoding:NSUTF8StringEncoding] name:@"client"];} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {[CommonUtils hideHudForView:self.view];NSLog(@"%@",responseObject);NSString *status = responseObject[@"status"];NSString *msg = responseObject[@"msg"];if ([status integerValue] == 1) {//登录成功,保存用户数据,跳转实名认证;[[Account shareAccount] saveUserInfo:responseObject[@"data"]];[[NSUserDefaults standardUserDefaults] setObject:responseObject[@"data"][@"auth"] forKey:@"auth"];if ([responseObject[@"data"][@"verified"] isEqualToString:@"0"]) {UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Login" bundle:[NSBundle mainBundle]];AuthViewController *authVC = [sb instantiateViewControllerWithIdentifier:@"auth"];[self.navigationController pushViewController:authVC animated:YES];}else{[self.navigationController popToRootViewControllerAnimated:YES];}}else{[CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {NSLog(@"%@",error);[CommonUtils hideHudForView:self.view];[CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];}];}}- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.}- (IBAction)skipProvision:(UIButton *)sender {}-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{[_phone resignFirstResponder];[_authCode resignFirstResponder];}
#import "DepositViewController.h"#import "PayTypeViewController.h"#import "Home.h"#import "CommonUtils.h"#import "Account.h"#import "Pay.h"#import "Account.h"#import <AlipaySDK/AlipaySDK.h>#import "UserInfo.h"#import "WXApi.h"#import "WXApiObject.h"@interface DepositViewController ()@property (weak, nonatomic) IBOutlet UIButton *continueBtn;@property (weak, nonatomic) IBOutlet UIView *otherView;@property (weak, nonatomic) IBOutlet UIImageView *bgImg;@property (nonatomic,strong) UIView *coverView;@property (weak, nonatomic) IBOutlet UILabel *despositLabel;@property (nonatomic,strong) NSString *desposit;@property (weak, nonatomic) IBOutlet UIView *AlView;@property (weak, nonatomic) IBOutlet UIView *WXView;@property (weak, nonatomic) IBOutlet UIImageView *ALSelect;@property (weak, nonatomic) IBOutlet UIImageView *WXSelect;@property (nonatomic) BOOL isALPay;@end@implementation DepositViewController- (void)viewDidLoad {[super viewDidLoad];[self setOtherView];[self requestDeposit];[self setUpNav];[self setUpPayView];[self drawColor];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closePage) name:@"finishWXPay" object:nil];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxErr) name:@"wxpayerr" object:nil];}-(void)viewWillAppear:(BOOL)animated{[super viewWillAppear:animated];self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};}-(void)viewWillDisappear:(BOOL)animated{[super viewWillDisappear:animated];self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor]};[self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:0];[self.navigationController.navigationBar setShadowImage:nil];}- (void)wxErr{[CommonUtils showTextHudModeWithInfo:@"支付失败" view:self.view stayTime:1.5];}- (void)setUpPayView{UITapGestureRecognizer *tapGestureRecognizer2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectALPay)];[_AlView addGestureRecognizer:tapGestureRecognizer2];_isALPay = YES;UITapGestureRecognizer *tapGestureRecognizer3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectWXPay)];[_WXView addGestureRecognizer:tapGestureRecognizer3];}- (void)selectALPay{_ALSelect.image = [UIImage imageNamed:@"withdraw_success"];_WXSelect.image = [UIImage imageNamed:@"Unchecked"];_isALPay = YES;}- (void)selectWXPay{_ALSelect.image = [UIImage imageNamed:@"Unchecked"];_WXSelect.image = [UIImage imageNamed:@"withdraw_success"];_isALPay = NO;}- (void)setUpNav{self.navigationController.navigationBar.hidden = NO;self.title = @"缴纳押金";UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];left.image = [UIImage imageNamed:@"back"];left.tintColor = [UIColor whiteColor];self.navigationItem.leftBarButtonItem = left;[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];[self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];}- (void)close{if (_isFromLogin) {[self closePage];}else{[self.navigationController popViewControllerAnimated:YES];}}- (void)setOtherView{self.navigationController.navigationBar.hidden = YES;_continueBtn.layer.cornerRadius = _continueBtn.bounds.size.height/2;_continueBtn.clipsToBounds = YES;;_coverView = [[UIView alloc] initWithFrame:self.view.bounds];[self.view addSubview:_coverView];_coverView.backgroundColor = [UIColor whiteColor];[self.view bringSubviewToFront:_coverView];}- (void)drawColor{CAGradientLayer *gradientLayer = [CAGradientLayer layer];UIColor *beginColor = [UIColor colorWithRed:210.f/255.f green:20/255.f blue:25.f/255.f alpha:1];UIColor *endColor = [UIColor colorWithRed:240.f/255.f green:130.f/255.f blue:45.f/255.f alpha:1];gradientLayer.colors = @[(__bridge id)beginColor.CGColor, (__bridge id)endColor.CGColor];gradientLayer.locations = @[@0.1,@1.0];gradientLayer.startPoint = CGPointMake(0, 0);gradientLayer.endPoint = CGPointMake(1.0, 0);gradientLayer.frame = CGRectMake(0, 0, kScreenW, _continueBtn.bounds.size.height);[self.continueBtn.layer addSublayer:gradientLayer];}- (void)requestDeposit{[CommonUtils showLoadingHudModelWithView:self.view handle:nil];NSString *url = [kBaseUrl stringByAppendingPathComponent:kGetDeposit];NSString *SIGN = [CommonUtils getSign];NSString *AUTH = [Account shareAccount].user.auth;AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];[manager POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {[CommonUtils hideHudForView:self.view];NSLog(@"%@",responseObject);NSString *status = responseObject[@"status"];NSString *msg = responseObject[@"msg"];if ([status integerValue] == 1) {_coverView.hidden = YES;_despositLabel.text = [NSString stringWithFormat:@"%.2f",[responseObject[@"data"] floatValue]/100];_desposit = [NSString stringWithFormat:@"%.2f元",[responseObject[@"data"] floatValue]/100];}else{[CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {\NSLog(@"%@",error);[CommonUtils hideHudForView:self.view];[CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];}];}- (void)closePage{[self.navigationController popToRootViewControllerAnimated:YES];}- (IBAction)next:(UIButton *)sender {// UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Login" bundle:[NSBundle mainBundle]];// PayTypeViewController *vc = [sb instantiateViewControllerWithIdentifier:@"payType"];// vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;// vc.isFromLogin = _isFromLogin;// vc.price = _desposit;// [self presentViewController:vc animated:YES completion:nil];[self payDeposit];}#pragma mark - 支付- (void)payDeposit{[CommonUtils showLoadingHudModelWithView:self.view handle:nil];NSString *url = [kBaseUrl stringByAppendingPathComponent:kPaydeposit];NSString *SIGN = [CommonUtils getSign];NSString *AUTH = [Account shareAccount].user.auth;AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {//参数NSString *payment;if (_isALPay) {payment = @"1";}else{payment = @"2";}[formData appendPartWithFormData:[payment dataUsingEncoding:NSUTF8StringEncoding] name:@"payment"];} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {NSLog(@"%@",responseObject);[CommonUtils hideHudForView:self.view];NSString *status = responseObject[@"status"];NSString *msg = responseObject[@"msg"];if ([status integerValue] == 1) {//验证成功if (_isALPay) {[self AliPay:responseObject];}else{[self WXPay:responseObject[@"data"]];}}else{[CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {NSLog(@"%@",error);[CommonUtils hideHudForView:self.view];[CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];}];}- (void)AliPay:(NSDictionary *)responseObject{//应用注册scheme,在AliSDKDemo-Info.plist定义URL typesNSString *appScheme = @"mengbei";// NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式NSString *orderString = responseObject[@"data"];// NOTE: 调用支付结果开始支付[[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {NSLog(@"reslut = %@",resultDic);NSString *statusCode = resultDic[@"resultStatus"];if ([statusCode isEqual:@"9000"]) {////关闭页面[CommonUtils showTextHudModeWithInfo:@"支付成功" view:self.view stayTime:1.5];[self closePage];//修改用户信息[Account shareAccount].user.hasdeposit = @"1";[[Account shareAccount] saveInfo];}else{[CommonUtils showTextHudModeWithInfo:@"支付失败" view:self.view stayTime:1.5];}}];}- (void)WXPay:(NSDictionary *)responseObject{PayReq *request = [[PayReq alloc] init] ;request.partnerId = responseObject[@"partnerid"];request.prepayId= responseObject[@"prepayid"];request.package = @"Sign=WXPay";request.nonceStr= responseObject[@"noncestr"];request.timeStamp= [responseObject[@"timestamp"] intValue];request.sign= responseObject[@"sign"];BOOL success = [WXApi sendReq:request];}- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.}
#import "PayTypeViewController.h"#import "CommonUtils.h"#import "Pay.h"#import "Account.h"#import <AlipaySDK/AlipaySDK.h>#import "UserInfo.h"#import "WXApi.h"#import "WXApiObject.h"#import <MapKit/MapKit.h>#import <AMapFoundationKit/AMapFoundationKit.h>//#import <AMapLocationKit/>@interface PayTypeViewController ()<UIGestureRecognizerDelegate>@property (weak, nonatomic) IBOutlet UIView *AlView;@property (weak, nonatomic) IBOutlet UIView *WXView;@property (weak, nonatomic) IBOutlet UIImageView *ALSelect;@property (weak, nonatomic) IBOutlet UIImageView *WXSelect;@property (weak, nonatomic) IBOutlet UIButton *payBtn;@property (weak, nonatomic) IBOutlet UIView *temView;@property (weak, nonatomic) IBOutlet UIView *bgView;@property (nonatomic) BOOL isALPay;@property (weak, nonatomic) IBOutlet UILabel *payTypeTitle;@property (weak, nonatomic) IBOutlet UILabel *payCount;@end@implementation PayTypeViewController- (void)viewDidLoad {[super viewDidLoad];_isALPay = YES;self.view.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.6];UITapGestureRecognizer *tapGestureRecognizer1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismisVC)];[self.view addGestureRecognizer:tapGestureRecognizer1];tapGestureRecognizer1.delegate = self;UITapGestureRecognizer *tapGestureRecognizer2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectALPay)];[_AlView addGestureRecognizer:tapGestureRecognizer2];UITapGestureRecognizer *tapGestureRecognizer3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectWXPay)];[_WXView addGestureRecognizer:tapGestureRecognizer3];//wxpayerr[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closePage) name:@"finishWXPay" object:nil];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxErr) name:@"wxpayerr" object:nil];_payCount.text = _price;if (_isFromMall) {_payTypeTitle.text = @"需支付";}else{_payTypeTitle.text = @"缴纳押金(可退)";}}//- (void)setUserLocalion{// MAUserLocationRepresentation *r = [[MAUserLocationRepresentation alloc] init];// r.showsAccuracyRing = NO;///精度圈是否显示,默认YES//}- (void)wxErr{[CommonUtils showTextHudModeWithInfo:@"支付失败" view:self.view stayTime:1.5];}-(void)dismisVC{[self dismissViewControllerAnimated:YES completion:nil];}- (void)selectALPay{_ALSelect.image = [UIImage imageNamed:@"withdraw_success"];_WXSelect.image = [UIImage imageNamed:@"Unchecked"];_isALPay = YES;}- (void)selectWXPay{_ALSelect.image = [UIImage imageNamed:@"Unchecked"];_WXSelect.image = [UIImage imageNamed:@"withdraw_success"];_isALPay = NO;}- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{if ( [touch.view isDescendantOfView:_bgView]) {return NO;}return YES;}- (void)payDeposit{[CommonUtils showLoadingHudModelWithView:self.view handle:nil];NSString *url = [kBaseUrl stringByAppendingPathComponent:kPaydeposit];NSString *SIGN = [CommonUtils getSign];NSString *AUTH = [Account shareAccount].user.auth;AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {//参数NSString *payment;if (_isALPay) {payment = @"1";}else{payment = @"2";}[formData appendPartWithFormData:[payment dataUsingEncoding:NSUTF8StringEncoding] name:@"payment"];} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {NSLog(@"%@",responseObject);[CommonUtils hideHudForView:self.view];NSString *status = responseObject[@"status"];NSString *msg = responseObject[@"msg"];if ([status integerValue] == 1) {//验证成功if (_isALPay) {[self AliPay:responseObject];}else{[self WXPay:responseObject[@"data"]];}}else{[CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {NSLog(@"%@",error);[CommonUtils hideHudForView:self.view];[CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];}];}- (void)payMallGoods{[CommonUtils showLoadingHudModelWithView:self.view handle:nil];NSString *url = [kBaseUrl stringByAppendingPathComponent:kAddGoodsOrder];[CommonUtils sendPOST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {[formData appendPartWithFormData:[_goodsNo dataUsingEncoding:NSUTF8StringEncoding] name:@"goodsNo"];[formData appendPartWithFormData:[_phone dataUsingEncoding:NSUTF8StringEncoding] name:@"phone"];[formData appendPartWithFormData:[_address dataUsingEncoding:NSUTF8StringEncoding] name:@"address"];[formData appendPartWithFormData:[_name dataUsingEncoding:NSUTF8StringEncoding] name:@"name"];[formData appendPartWithFormData:[_postal dataUsingEncoding:NSUTF8StringEncoding] name:@"postal"];if (_isALPay) {[formData appendPartWithFormData:[@"1" dataUsingEncoding:NSUTF8StringEncoding] name:@"pay"];}else{[formData appendPartWithFormData:[@"0" dataUsingEncoding:NSUTF8StringEncoding] name:@"pay"];}} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {NSLog(@"%@",responseObject);[CommonUtils hideHudForView:self.view];NSString *status = responseObject[@"status"];NSString *msg = responseObject[@"msg"];if ([status integerValue] == 1) {//验证成功if (_isALPay) {[self AliPay:responseObject];}else{[self WXPay:responseObject[@"data"]];}}else{[CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {NSLog(@"%@",error);[CommonUtils hideHudForView:self.view];[CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];}];}- (IBAction)pay:(UIButton *)sender {if (_isFromMall) {[self payMallGoods];}else{[self payDeposit];}}- (void)closePage{//修改用户信息[Account shareAccount].user.hasdeposit = @"1";[[Account shareAccount] saveInfo];[self dismissViewControllerAnimated:YES completion:^{}];UINavigationController *nav = (UINavigationController *)self.presentingViewController;[nav popToRootViewControllerAnimated:YES];}- (void)AliPay:(NSDictionary *)responseObject{//应用注册scheme,在AliSDKDemo-Info.plist定义URL typesNSString *appScheme = @"mengbei";// NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式NSString *orderString = responseObject[@"data"];// NOTE: 调用支付结果开始支付[[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {NSLog(@"reslut = %@",resultDic);NSString *statusCode = resultDic[@"resultStatus"];if ([statusCode isEqual:@"9000"]) {////关闭页面[CommonUtils showTextHudModeWithInfo:@"支付成功" view:self.view stayTime:1.5];[self closePage];//修改用户信息[Account shareAccount].user.hasdeposit = @"1";[[Account shareAccount] saveInfo];}else{[CommonUtils showTextHudModeWithInfo:@"支付失败" view:self.view stayTime:1.5];}}]}- (void)WXPay:(NSDictionary *)responseObject{PayReq *request = [[PayReq alloc] init] ;request.partnerId = responseObject[@"partnerid"];request.prepayId= responseObject[@"prepayid"];request.package = @"Sign=WXPay";request.nonceStr= responseObject[@"noncestr"];request.timeStamp= [responseObject[@"timestamp"] intValue];request.sign= responseObject[@"sign"];BOOL success = [WXApi sendReq:request];}
#import "CommonUtils.h"#import <MBProgressHUD.h>#import <SAMKeychain.h>#import "CommonCrypto/CommonDigest.h"#import "sys/utsname.h"@implementation CommonUtils+(BOOL)isIDCard:(NSString *)identityString{if (identityString.length != 18) return NO;// 正则表达式判断基本 身份证号是否满足格式NSString *regex = @"^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";// NSString *regex = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";NSPredicate *identityStringPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];//如果通过该验证,说明身份证格式正确,但准确性还需计算if(![identityStringPredicate evaluateWithObject:identityString]) return NO;//** 开始进行校验 *////将前17位加权因子保存在数组里NSArray *idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];//这是除以11后,可能产生的11位余数、验证码,也保存成数组NSArray *idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];//用来保存前17位各自乖以加权因子后的总和NSInteger idCardWiSum = 0;for(int i = 0;i < 17;i++) {NSInteger subStrIndex = [[identityString substringWithRange:NSMakeRange(i, 1)] integerValue];NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];idCardWiSum+= subStrIndex * idCardWiIndex;}//计算出校验码所在数组的位置NSInteger idCardMod=idCardWiSum%11;//得到最后一位身份证号码NSString *idCardLast= [identityString substringWithRange:NSMakeRange(17, 1)];//如果等于2,则说明校验码是10,身份证号码最后一位应该是Xif(idCardMod==2) {if(![idCardLast isEqualToString:@"X"]|| ![idCardLast isEqualToString:@"x"]) {return NO;}}else{//用计算出的验证码与最后一位身份证号码匹配,如果一致,说明通过,否则是无效的身份证号码if(![idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]]) {return NO;}}return YES;}+(BOOL)isPhoneNum:(NSString *)phone{NSString *predicate = @"^[1][3,4,5,6,7,8][0-9]{9}$";// @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[06-8])\\d{8}$";NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", predicate];return [regextestmobile evaluateWithObject:phone];}+(void)showTextHudModeWithInfo:(NSString *)infoStr view:(UIView *)view stayTime:(float)time{MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];hud.mode = MBProgressHUDModeText;hud.label.text = infoStr;hud.offset = CGPointMake(1.f, 230);hud.contentColor = [UIColor whiteColor];hud.bezelView.color= [UIColor blackColor];hud.label.font = [UIFont systemFontOfSize:14];hud.minSize = CGSizeMake(100, 30);[hud hideAnimated:YES afterDelay:time];}+ (void)showLoadingHudModelWithView:(UIView *)view handle:(void (^)(void))dosome{MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];hud.mode = MBProgressHUDModeIndeterminate;}+ (void)showLoadingHudWithView:(UIView *)view text:(NSString *)text{MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];hud.mode = MBProgressHUDModeIndeterminate;hud.detailsLabel.text = text;}+(void)hideHudForView:(UIView *)view{[MBProgressHUD hideHUDForView:view animated:YES];}+(AFHTTPSessionManager *)getAFHTTPSessionManager{AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];manager.responseSerializer = [AFHTTPResponseSerializer serializer];manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/javascript", @"text/html",@"image/png",nil];manager.requestSerializer = [AFHTTPRequestSerializer serializer];manager.responseSerializer =[AFJSONResponseSerializer serializer];//以json格式返回manager.requestSerializer = [AFJSONRequestSerializer serializer];//以json格式提交manager.requestSerializer.timeoutInterval = 10.0f;return manager;}+(void)sendPOST:(NSString *)URLString parameters:(id)parameters constructingBodyWithBlock:(void (^)(id<AFMultipartFormData>))block progress:(void (^)(NSProgress * _Nonnull))uploadProgress success:(void (^)(NSURLSessionDataTask *, id))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure{AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];manager.responseSerializer = [AFHTTPResponseSerializer serializer];manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/javascript", @"text/html",@"image/png",nil];manager.requestSerializer = [AFHTTPRequestSerializer serializer];manager.responseSerializer =[AFJSONResponseSerializer serializer];//以json格式返回manager.requestSerializer = [AFJSONRequestSerializer serializer];//以json格式提交manager.requestSerializer.timeoutInterval = 10.0f;NSString *SIGN = [CommonUtils getSign];NSString *AUTH = [Account shareAccount].user.auth;[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];[manager POST:URLString parameters:parameters constructingBodyWithBlock:block progress:uploadProgress success:success failure:failure];}+(void)sendNobodyPOST:(NSString *)URLString parameters:(id)parameters progress:(void (^)(NSProgress * _Nonnull))uploadProgress success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nullable))failure{AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];manager.responseSerializer = [AFHTTPResponseSerializer serializer];manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/javascript", @"text/html",@"image/png",nil];manager.requestSerializer = [AFHTTPRequestSerializer serializer];manager.responseSerializer =[AFJSONResponseSerializer serializer];//以json格式返回manager.requestSerializer = [AFJSONRequestSerializer serializer];//以json格式提交manager.requestSerializer.timeoutInterval = 10.0f;NSString *SIGN = [CommonUtils getSign];NSString *AUTH = [Account shareAccount].user.auth;[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];[manager POST:URLString parameters:parameters progress:uploadProgress success:success failure:failure];}+(NSString *)getDeviceUUID{NSString *uuid = [SAMKeychain passwordForService:@"" account:@"uuid"];if (uuid == nil || [uuid isEqual:@""]) {NSUUID *curentuuid = [[UIDevice currentDevice] identifierForVendor];uuid = [curentuuid UUIDString];uuid = [uuid stringByReplacingOccurrencesOfString:@"-" withString:@""];[SAMKeychain setPassword:uuid forService:@"" account:@"uuid"];}return uuid;}+(NSString *)getNowTimestamp{NSDate *nowDate = [NSDate dateWithTimeIntervalSinceNow:0];NSTimeInterval time = [nowDate timeIntervalSince1970] *1000;NSString *timestamp = [NSString stringWithFormat:@"%.0f",time];return timestamp;}+(NSString *)getMD5StrWithString:(NSString *)str{const char *cStr = [str UTF8String];unsigned char digest[CC_MD5_DIGEST_LENGTH];CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {[result appendFormat:@"%02x", digest[i]];}return result;}+(NSString *)getSign{//时间戳NSString *timestamp = [self getNowTimestamp];NSString *key = @"Mombo@Zhou";NSString *temStr = [NSString stringWithFormat:@"%@.%@",key,timestamp];NSString *md5Str = [self getMD5StrWithString:temStr];NSString *sign = [NSString stringWithFormat:@"%@.%@",timestamp,md5Str];return sign;}+(float)getDifSinceNowWithTimetamp:(NSString *)timetamp{NSDate* nowdate = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间NSTimeInterval time=[nowdate timeIntervalSince1970]*1000;// *1000 是精确到毫秒,不乘就是精确到秒float tem = (time-[timetamp floatValue]);if (tem < 0) {return 0;}else{return tem;}}+ (void)showAlertWithTitle:(NSString *)title alertMessage:(NSString *)message action1Title:(NSString *)title1 action1Stytle:(UIAlertActionStyle)style1 action1Handler:(void (^ __nullable)(UIAlertAction *action))handler1 action2Title:(NSString *)title2 action1Stytle:(UIAlertActionStyle)style2 action1Handler:(void (^ __nullable)(UIAlertAction *action))handler2 presentVC:(UIViewController *)VC{UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];UIAlertAction *act1 = [UIAlertAction actionWithTitle:title1 style:style1 handler:handler1];UIAlertAction *act2 = [UIAlertAction actionWithTitle:title2 style:style2 handler:handler2];[alert addAction:act1];[alert addAction:act2];[VC presentViewController:alert animated:YES completion:nil];}+ (CGFloat)getStringHeightWithFontSize:(CGFloat)font string:(NSString *)str andWidth:(CGFloat)height{UIFont *temp = [UIFont systemFontOfSize:font];NSDictionary *attributes = @{NSFontAttributeName : temp};CGRect sizeFit = [str boundingRectWithSize:CGSizeMake(height, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];return sizeFit.size.height;}+(BOOL)isiPhoneX{struct utsname systemInfo;uname(&systemInfo);NSString * deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];if ([deviceString containsString:@"iPhone10"]) {return YES;}else{return NO;}}
#import "LCBluetoothManager.h"#import "CommonUtils.h"#import "Account.h"#import "Home.h"#import "LocationManager.h"typedef NS_ENUM(NSInteger,BLEWriteStatus){WriteOpen = 0,WriteQuery,NormalStaus};BOOL IsBlueToothOpen = NO;@interface LCBluetoothManager ()<CBCentralManagerDelegate,CBPeripheralDelegate>@property (nonatomic,strong) CBPeripheral *peripheral;@property (nonatomic,strong) CBCentralManager *centralManager;@property (nonatomic,strong) CBCharacteristic *characteristic;@property (nonatomic,assign) BLEWriteStatus writeStatus;@property (nonatomic,strong) NSTimer *timer;@property (nonatomic) BOOL isSendCancle;@end@implementation LCBluetoothManager+(instancetype)sharedManager{static LCBluetoothManager *sharedManager;static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{sharedManager = [[self alloc] init];});return sharedManager;}+ (BOOL)isBlueOpen{return IsBlueToothOpen;}-(instancetype)init{if (self == [super init]) {_writeStatus = NormalStaus;}return self;}//开锁-(void)openLock{_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];_writeStatus = NormalStaus;}//连接指定车锁-(void)connectBTEWtihLockNo:(NSString *)lockNo{//请求开锁密钥// [self.centralManager cancelPeripheralConnection:_peripheral];_lockno = lockNo;[self openLock];}-(void)cancelPeripheralConnection{if (_peripheral) {_conectedState = DisconnectStateWithCancle;[self.centralManager cancelPeripheralConnection:_peripheral];}}//请求服务器是否开锁成功- (void)checkRent{NSString *url = [kBaseUrl stringByAppendingPathComponent:kCheckRent];NSString *SIGN = [CommonUtils getSign];NSString *AUTH = [Account shareAccount].user.auth;AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {[formData appendPartWithFormData:[_rentid dataUsingEncoding:NSUTF8StringEncoding] name:@"rentid"];[formData appendPartWithFormData:[_lockno dataUsingEncoding:NSUTF8StringEncoding] name:@"lockno"];[formData appendPartWithFormData:[_rentposition dataUsingEncoding:NSUTF8StringEncoding] name:@"rentposition"];} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {NSLog(@"%@",responseObject);NSString *status = responseObject[@"status"];NSString *msg = responseObject[@"msg"];if ([status integerValue] == 1) {[[NSNotificationCenter defaultCenter] postNotificationName:kOpenLockSuccess object:nil];//开始记录轨迹[[LocationManager sharedLocationManager] startSaveRoute];}else{}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {NSLog(@"%@",error);}];}#pragma mark CoreBluetoothDelegate//外设//中心设备- (void)centralManagerDidUpdateState:(CBCentralManager *)central{switch (central.state) {case CBCentralManagerStatePoweredOn:{IsBlueToothOpen = YES;//扫描外设(discover)NSLog(@"蓝牙可用");// 根据SERVICE_UUID来扫描外设,如果不设置SERVICE_UUID,则扫描所有蓝牙设备// [_centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:SERVICES_UUID]] options:nil];//34AD9190-6055-28BB-B916-87A805513A66CBUUID *uuid = [CBUUID UUIDWithString:@"34AD9190-6055-28BB-B916-87A805513A66"];if (_lockno) {[central scanForPeripheralsWithServices:nil options:nil];}}break;default:[CommonUtils showTextHudModeWithInfo:@"蓝牙连接断开" view:[UIApplication sharedApplication].keyWindow.rootViewController.view stayTime:1.0];_conectedState = DisconnectStateWithNoCancle;break;}}/** 发现符合要求的外设,回调 */- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {// 对外设对象进行强引用NSLog(@"当扫描到设备:%@",peripheral.name);//10秒钟扫描不到设备 停止扫描if (_timer == nil) {_timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(cancelScan) userInfo:nil repeats:NO];}if ([peripheral.name isEqualToString:[NSString stringWithFormat:@"DB%@",_lockno]]) {self.peripheral = peripheral;[_centralManager cancelPeripheralConnection:peripheral];[_centralManager connectPeripheral:self.peripheral options:nil];}}- (void)cancelScan{// [_centralManager stopScan];[[NSNotificationCenter defaultCenter] postNotificationName:kStopScap object:nil];[_timer invalidate];_timer = nil;[CommonUtils showTextHudModeWithInfo:@"扫描不到可用蓝牙信息" view:[UIApplication sharedApplication].keyWindow.rootViewController.view stayTime:1.5];}/** 连接成功 */- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{// 可以停止扫描[self.centralManager stopScan];// 设置代理self.peripheral.delegate = self;// 根据UUID来寻找服务// _peripheral whri_peripheral = peripheral;[_peripheral discoverServices:@[[CBUUID UUIDWithString:@"1960"]]];_conectedState = ConnectedState;NSLog(@"连接成功");}/** 连接失败的回调 */-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {NSLog(@"连接失败");//定时重连_conectedState = DisconnectStateWithNoCancle;}/** 断开连接 */- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error {NSLog(@"断开连接");if (_conectedState == DisconnectStateWithNoCancle) {//非正常取消连接[CommonUtils showTextHudModeWithInfo:@"蓝牙连接断开" view:[UIApplication sharedApplication].keyWindow.rootViewController.view stayTime:1.0];//重连机制if (_peripheral) {[central connectPeripheral:peripheral options:nil];}}else{//正常取消连接_lockno = nil;_conectedState = DisconnectStateWithCancle;}}/** 发现服务 */- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {// 遍历出外设中所有的服务for (CBService *service in peripheral.services) {NSLog(@"所有的服务uuid:%@",service.UUID);if ([service.UUID.UUIDString isEqual:@"1960"]) {// [_peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:WRITE_UUID]] forService:service];[peripheral discoverCharacteristics:nil forService:service];}}}/** 发现特征回调 */- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {// 遍历出所需要的特征for (CBCharacteristic *characteristic in service.characteristics) {if ([characteristic.UUID.UUIDString isEqual:@"2BB2"]){[peripheral setNotifyValue:YES forCharacteristic:characteristic];[peripheral discoverDescriptorsForCharacteristic:characteristic];}}for (CBCharacteristic *characteristic in service.characteristics) {NSLog(@"所有特征:%@", characteristic.UUID);if ([characteristic.UUID.UUIDString isEqual:@"2BB1"]) {_characteristic = characteristic;;if (_isReconnected || _conectedState == DisconnectStateWithNoCancle) {//查询是否关锁// [_peripheral writeValue:[@"0100" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];//aa0200000001dd544a000000000000000000c055NSString *queryKey = [[NSUserDefaults standardUserDefaults] objectForKey:kQuerykey];NSData *data = [self convertHexStrToData:queryKey];[_peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];[_peripheral readValueForCharacteristic:self.characteristic];_writeStatus = WriteQuery;}else if(_secretkey){NSData *data = [self convertHexStrToData:_secretkey];[_peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];_writeStatus = WriteOpen;[_peripheral readValueForCharacteristic:self.characteristic];}}else{[peripheral setNotifyValue:YES forCharacteristic:characteristic];}}}-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{//打印出Characteristic和他的DescriptorsNSLog(@"characteristic uuid:%@",characteristic.UUID);for (CBDescriptor *d in characteristic.descriptors) {NSLog(@"Descriptor uuid:%@",d.UUID);// [peripheral setNotifyValue:YES forCharacteristic:characteristic];// [peripheral writeValue:[@"0100" dataUsingEncoding:NSUTF8StringEncoding] forDescriptor:d];}}/** 订阅状态的改变 */-(void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {NSLog(@"111");if (error) {NSLog(@"订阅失败");NSLog(@"%@",error);}if (characteristic.isNotifying) {NSLog(@"订阅成功");} else {NSLog(@"取消订阅");}}/** 接收到数据回调 */- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {// 拿到外设发送过来的数据NSData *data = characteristic.value;NSString *str = [self convertDataToHexStr:data];//aa01000000057e63a6000000000000000000bf55 开锁成功//aa1f405010000000057e63a6000000000000a155 关锁NSLog(@"蓝牙返回的数据:%@ 特征:%@",str,characteristic.UUID);// NSString *openLockStr = [str substringWithRange:NSMakeRange(2, 2)];if ([characteristic.UUID.UUIDString isEqual:@"2BB2"]) {switch (_writeStatus) {case WriteOpen://向蓝牙发送开锁命令后收到的回掉数据{_writeStatus = NormalStaus;NSString *openLockStr = [str substringWithRange:NSMakeRange(8, 2)];if ([openLockStr isEqualToString:@"01"]) {//向锁发送查询命令[self checkRent];}}break;case WriteQuery:// 向蓝牙发送查询命令后收到的回掉数据{_isReconnected = NO;_writeStatus = NormalStaus;NSString *queryStr = [str substringWithRange:NSMakeRange(24, 2)];if ([queryStr isEqualToString:@"01"]) {//蓝牙回应:已开锁}else{[[NSNotificationCenter defaultCenter] postNotificationName:kCloseLock object:nil userInfo:@{@"rentid":_rentid,@"lockno":_lockno}];}}break;case NormalStaus://未向蓝牙发送任何数据,收到蓝牙回调数据,用户主动关锁,会回调此处{NSString *closeLockStr = [str substringWithRange:NSMakeRange(7, 2)];if ([closeLockStr isEqualToString:@"01"]) {//关锁成功[[NSNotificationCenter defaultCenter] postNotificationName:kCloseLock object:nil userInfo:@{@"rentid":_rentid,@"lockno":_lockno}];}}break;default:break;}}}/** 写入数据回调 */- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error {if (error) {NSLog(@"写入失败");}else{NSLog(@"写入成功");}}- (NSString *)convertDataToHexStr:(NSData *)data {if (!data || [data length] == 0) {return @"";}NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];[data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {unsigned char *dataBytes = (unsigned char*)bytes;for (NSInteger i = 0; i < byteRange.length; i++) {NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];if ([hexStr length] == 2) {[string appendString:hexStr];} else {[string appendFormat:@"0%@", hexStr];}}}]return string;}- (NSMutableData *)convertHexStrToData:(NSString *)str {if (!str || [str length] == 0) {return nil;}NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];NSRange range;if ([str length] %2 == 0) {range = NSMakeRange(0,2);} else {range = NSMakeRange(0,1);}for (NSInteger i = range.location; i < [str length]; i += 2) {unsigned int anInt;NSString *hexCharStr = [str substringWithRange:range];NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];[scanner scanHexInt:&anInt];NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];[hexData appendData:entity];range.location += range.length;range.length = 2;}return hexData;}
import "UserTableViewController.h"#import "BabyFooterViewController.h"#import "Account.h"#import "MallCollectionViewController.h"#import "SettingTableViewController.h"#import "WebViewController.h"#import "MessageTableViewController.h"@interface UserTableViewController ()@property (weak, nonatomic) IBOutlet UITableViewCell *walletCell;@property (nonatomic,strong) UIView *topView;@property (weak, nonatomic) IBOutlet UIView *view1;@property (weak, nonatomic) IBOutlet UIView *view2;@property (weak, nonatomic) IBOutlet UILabel *useCount;@property (weak, nonatomic) IBOutlet UILabel *credit;@property (weak, nonatomic) IBOutlet UIView *headView;@property (weak, nonatomic) IBOutlet UILabel *userName;@property (weak, nonatomic) IBOutlet NSLayoutConstraint *headViewHeight;@end@implementation UserTableViewController- (void)viewDidLoad {[super viewDidLoad];}-(void)viewWillAppear:(BOOL)animated{[super viewWillAppear:animated];self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];[self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];[self setUpNav];if ([CommonUtils isiPhoneX]) {_headViewHeight.constant = 90+30;}else{_headViewHeight.constant = 90;}[self drawColor];[self setUpTableview];[self setUpUserInfo];}-(void)viewWillDisappear:(BOOL)animated{[super viewWillDisappear:animated];self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor]};[self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:0];[self.navigationController.navigationBar setShadowImage:nil];}-(void)viewDidDisappear:(BOOL)animated{[super viewDidDisappear:animated];}- (void)setUpUserInfo{_userName.text = [[Account shareAccount].user.mobile stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];}- (void)setUpTableview{_walletCell.detailTextLabel.text = [NSString stringWithFormat:@"%.f 元",[[Account shareAccount].user.money floatValue]/100];self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];self.tableView.scrollEnabled =NO;self.automaticallyAdjustsScrollViewInsets = NO;// self.tableView.contentInset = UIEdgeInsetsMake(-70, 0, 0, 0);}- (void)drawColor{CAGradientLayer *gradientLayer = [CAGradientLayer layer];UIColor *beginColor = [UIColor colorWithRed:210.f/255.f green:20/255.f blue:25.f/255.f alpha:1];UIColor *endColor = [UIColor colorWithRed:240.f/255.f green:130.f/255.f blue:45.f/255.f alpha:1];gradientLayer.colors = @[(__bridge id)beginColor.CGColor, (__bridge id)endColor.CGColor];gradientLayer.locations = @[@0.1,@1.0];gradientLayer.startPoint = CGPointMake(0, 0);gradientLayer.endPoint = CGPointMake(1.0, 0);gradientLayer.frame = CGRectMake(0, 0, kScreenW, _headViewHeight.constant);[self.headView.layer addSublayer:gradientLayer];}- (void)setUpNav{self.navigationController.navigationBar.hidden = NO;self.title = @"个人中心";UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];left.image = [UIImage imageNamed:@"back"];left.tintColor = [UIColor whiteColor];self.navigationItem.leftBarButtonItem = left;UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(setting)];right.image = [UIImage imageNamed:@"设置"];right.tintColor = [UIColor whiteColor];self.navigationItem.rightBarButtonItem = right;;}- (void)setting{UIStoryboard *sb = [UIStoryboard storyboardWithName:@"User" bundle:[NSBundle mainBundle]];SettingTableViewController *vc = [sb instantiateViewControllerWithIdentifier:@"setting"];[self.navigationController pushViewController:vc animated:YES];}- (void)close{[self.navigationController popViewControllerAnimated:YES];}
#import "BabyFooterViewController.h"#import "BabyFooterFirstTableViewCell.h"#import "BabyFootSecondTableViewCell.h"#import "FooterViewController.h"#import "Home.h"#import <MAMapKit/MAMapKit.h>#import "Recommend.h"#import "LocationManager.h"@interface BabyFooterViewController ()<UITableViewDelegate,UITableViewDataSource>@property (weak, nonatomic) IBOutlet UITableView *tableView;@property (nonatomic,strong) Recommend *recommendData;@end@implementation BabyFooterViewController- (void)viewDidLoad {[super viewDidLoad];[self setUpTableView];[self setUpNav];[self requesData];}- (void)setUpNav{self.navigationController.navigationBar.hidden = NO;self.title = @"宝宝足迹";UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];left.image = [UIImage imageNamed:@"back"];left.tintColor = [UIColor blackColor];self.navigationItem.leftBarButtonItem = left;}- (void)requesData{[CommonUtils showLoadingHudWithView:self.view text:nil];NSString *url = [kBaseUrl stringByAppendingPathComponent:kGetFooterFences];[CommonUtils sendPOST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {NSString *city = [LocationManager sharedLocationManager].loctionInfo.city;if (city == nil) {[formData appendPartWithFormData:[@"武汉市" dataUsingEncoding:NSUTF8StringEncoding] name:@"cityName"];}else{[formData appendPartWithFormData:[city dataUsingEncoding:NSUTF8StringEncoding] name:@"cityName"];}} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {NSLog(@"%@",responseObject);NSString *status = responseObject[@"status"];NSString *msg = responseObject[@"msg"];[CommonUtils hideHudForView:self.view];if ([status integerValue] == 1) {_recommendData = [[Recommend alloc] initRecommend:responseObject[@"data"]];[self.tableView reloadData];}else{[CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {NSLog(@"%@",error);[CommonUtils hideHudForView:self.view];[CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];}];}- (void)close{[self.navigationController popViewControllerAnimated:YES];}- (void)setUpTableView{[self.tableView registerNib:[UINib nibWithNibName:@"BabyFooterFirstTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"BabyFooterFirstTableViewCell"];[self.tableView registerNib:[UINib nibWithNibName:@"BabyFootSecondTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"BabyFootSecondTableViewCell"];self.tableView.delegate = self;self.tableView.dataSource = self;self.tableView.estimatedRowHeight = 0;self.tableView.estimatedSectionHeaderHeight = 0;self.tableView.estimatedSectionFooterHeight = 0;// self.tableView.dataSource = self;self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectNull];}- (void)skipMoreFooter{}- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.}#pragma mark - Table view data source- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {return 2;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {switch (section) {case 0:return _recommendData.footArr.count;break;case 1:return _recommendData.fenceArr.count;break;default:return 0;break;}}-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{switch (indexPath.section) {case 0:return 120;break;case 1:return 120;break;default:return 0;break;}}-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{return 0.1;}-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{switch (section) {case 0:return 10;break;default:return 0;break;}}- (NSString *)getTimeStrWithTimetap:(NSString *)timetamp{NSDateFormatter *stampFormatter = [[NSDateFormatter alloc] init];[stampFormatter setDateFormat:@"YYYY-MM-dd HH:mm"];//以 1970/01/01 GMT为基准,然后过了secs秒的时间NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timetamp integerValue]/1000];NSString *timeStr = [stampFormatter stringFromDate:date];return timeStr;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {if (indexPath.section == 0) {BabyFooterFirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BabyFooterFirstTableViewCell" forIndexPath:indexPath];cell.backView.layer.borderWidth = 1;cell.backView.layer.borderColor = [UIColor blackColor].CGColor;cell.backView.layer.cornerRadius = 3;cell.clipsToBounds = YES;cell.selectionStyle = UITableViewCellSelectionStyleNone;cell.separatorInset = UIEdgeInsetsMake(0, kScreenW, 0, 0);cell.address.text = _recommendData.footArr[indexPath.row].address;//时间NSString *startTime = [self getTimeStrWithTimetap:_recommendData.footArr[indexPath.row].renttime];NSString *rturnTime = [self getTimeStrWithTimetap:_recommendData.footArr[indexPath.row].returntime];cell.time.text = [NSString stringWithFormat:@"%@~%@",startTime,rturnTime];return cell;}else{BabyFootSecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BabyFootSecondTableViewCell" forIndexPath:indexPath];cell.selectionStyle = UITableViewCellSelectionStyleNone;cell.name.text = _recommendData.fenceArr[indexPath.row].name;cell.address.text =[NSString stringWithFormat:@"%@ %@",_recommendData.fenceArr[indexPath.row].address,_recommendData.fenceArr[indexPath.row].describe];cell.lockCount.text = [NSString stringWithFormat:@"剩余%@辆",_recommendData.fenceArr[indexPath.row].lockCount];MAMapPoint point1 = MAMapPointForCoordinate(CLLocationCoordinate2DMake([LocationManager sharedLocationManager].latitude,[LocationManager sharedLocationManager].longitude));MAMapPoint point2 = MAMapPointForCoordinate(CLLocationCoordinate2DMake([_recommendData.fenceArr[indexPath.row].latitude floatValue],[_recommendData.fenceArr[indexPath.row].longitude floatValue]));//2.计算距离CLLocationDistance distance = MAMetersBetweenMapPoints(point1,point2)/1000.f;cell.distance.text = [NSString stringWithFormat:@"%.2fkm",distance];return cell;}}//-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{//// if (section == 1 && _recommendData != nil) {//// UIView *head = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 30)];//// head.backgroundColor = [UIColor groupTableViewBackgroundColor];//// UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];//// btn.frame = CGRectMake(kScreenW-60,0 , 60, 30);//// [btn setTitle:@"更多" forState:UIControlStateNormal];//// [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];//// btn.titleLabel.font = [UIFont systemFontOfSize:14];//// [btn addTarget:self action:@selector(skipMoreFooter) forControlEvents:UIControlEventTouchUpInside];//// [head addSubview:btn];//// return head;//// }// UIView *head = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 30)];// head.backgroundColor = [UIColor groupTableViewBackgroundColor];// UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];// [head addSubview:titleLab];// titleLab.font = [UIFont systemFontOfSize:13];// titleLab.textColor = [UIColor blackColor];//// if (section == 0) {// titleLab.text = @"宝贝行程";// }else{// titleLab.text = @"商圈推荐";// }// return head;//}-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{switch (indexPath.section) {case 0:{UIStoryboard *sb = [UIStoryboard storyboardWithName:@"User" bundle:[NSBundle mainBundle]];FooterViewController *vc = [sb instantiateViewControllerWithIdentifier:@"babyFooter"];vc.rentId = _recommendData.footArr[indexPath.row].rentid;[self.navigationController pushViewController:vc animated:YES];}break;default:break;}}- (void)scrollViewDidScroll:(UIScrollView *)scrollView{CGFloat sectionHeaderHeight = 30;//设置你footer高度if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);} else if (scrollView.contentOffset.y>=sectionHeaderHeight) {scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);}}
#import "RechargeViewController.h"#import "CommonUtils.h"#import "Pay.h"#import "Account.h"#import "Recharge.h"#import <AlipaySDK/AlipaySDK.h>#import "WXApiObject.h"#import "WXApi.h"#import "WebViewController.h"@interface RechargeViewController ()@property (weak, nonatomic) IBOutlet UIView *AlView;@property (weak, nonatomic) IBOutlet UIView *WXView;@property (weak, nonatomic) IBOutlet UIImageView *ALSelect;@property (weak, nonatomic) IBOutlet UIImageView *WXSelect;@property (nonatomic) BOOL isALPay;@property (weak, nonatomic) IBOutlet UIButton *btn1;@property (weak, nonatomic) IBOutlet UIButton *btn2;@property (weak, nonatomic) IBOutlet UIButton *btn3;@property (weak, nonatomic) IBOutlet UIButton *btn4;@property (weak, nonatomic) IBOutlet UIButton *btn5;@property (nonatomic,strong) NSString *payCount;@property (weak, nonatomic) IBOutlet UIView *coverView;@property (weak, nonatomic) IBOutlet UIView *rechargeView;@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rechargeViewHeight;@property (nonatomic,strong) NSMutableArray <Recharge *> *rechargeArr;@property (nonatomic,strong) NSMutableArray *rechargeBtnArr;@property (nonatomic,strong) NSString *rechargeid;@end#define kRechargeBtnH 50#define kRechargeBtnW ([UIScreen mainScreen].bounds.size.width - 24)/2@implementation RechargeViewController- (void)viewDidLoad {[super viewDidLoad];[self setUpNav];UITapGestureRecognizer *tapGestureRecognizer2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectALPay)];[_AlView addGestureRecognizer:tapGestureRecognizer2];_isALPay = YES;UITapGestureRecognizer *tapGestureRecognizer3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectWXPay)];[_WXView addGestureRecognizer:tapGestureRecognizer3];[self.view bringSubviewToFront:_coverView];[self getRecharge];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tip) name:@"finishWXPay" object:nil];}- (void)tip{[CommonUtils showTextHudModeWithInfo:@"充值成功" view:self.view stayTime:1.5];}- (void)setUpNav{self.navigationController.navigationBar.hidden = NO;self.title = @"充值";UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];left.image = [UIImage imageNamed:@"back"];left.tintColor = [UIColor blackColor];self.navigationItem.leftBarButtonItem = left;}- (void)close{[self.navigationController popViewControllerAnimated:YES];}#pragma mark - 网络请求- (void)getRecharge{[CommonUtils showLoadingHudModelWithView:self.view handle:nil];NSString *url = [kBaseUrl stringByAppendingPathComponent:kGetRecharge];NSString *SIGN = [CommonUtils getSign];NSString *AUTH = [Account shareAccount].user.auth;AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];[manager POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {[CommonUtils hideHudForView:self.view];NSLog(@"%@",responseObject);NSString *status = responseObject[@"status"];NSString *msg = responseObject[@"msg"];if ([status integerValue] == 1) {_coverView.hidden = YES;_rechargeArr = [NSMutableArray array];for (NSDictionary *dict in responseObject[@"data"]) {Recharge *recharge = [[Recharge alloc] initRecharge:dict];[_rechargeArr addObject:recharge];}_rechargeid = [NSString stringWithFormat:@"%@",_rechargeArr[0].rechageId];[self layoutRechargeBtnView];}else{[CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {[CommonUtils hideHudForView:self.view];[CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];}];}- (void)layoutRechargeBtnView{_rechargeViewHeight.constant = (_rechargeArr.count/2 + _rechargeArr.count%2)*(kRechargeBtnH+16)+16;_rechargeBtnArr = [NSMutableArray array];for (int i = 0; i < _rechargeArr.count; i++) {UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];btn.frame = CGRectMake(i%2*(kRechargeBtnW+8)+8, i/2*(kRechargeBtnH+16)+16, kRechargeBtnW, kRechargeBtnH);btn.layer.cornerRadius = kRechargeBtnH/2;btn.clipsToBounds = YES;//背景颜色if (i == 0) {btn.backgroundColor = [UIColor colorWithRed:237.f/255.f green:56.f/255.f blue:53.f/255.f alpha:1];}else{btn.backgroundColor = [UIColor colorWithRed:242.f/255.f green:242.f/255.f blue:242.f/255.f alpha:1];}NSString *btnTitle = [NSString stringWithFormat:@"%.2f元(赠送%.f元)",[_rechargeArr[i].recharge floatValue]/100.f,[_rechargeArr[i].gift floatValue]/100.f];[btn setTitle:btnTitle forState:UIControlStateNormal];btn.titleLabel.font = [UIFont systemFontOfSize:14];[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];btn.tag = 100+i;[btn addTarget:self action:@selector(clickRechargeBtn:) forControlEvents:UIControlEventTouchUpInside];[_rechargeBtnArr addObject:btn];[_rechargeView addSubview:btn];}}- (void)clickRechargeBtn:(UIButton *)sender{for (UIButton *btn in _rechargeBtnArr) {if (btn.tag == sender.tag) {btn.backgroundColor = [UIColor colorWithRed:237.f/255.f green:56.f/255.f blue:53.f/255.f alpha:1];;_rechargeid = [NSString stringWithFormat:@"%@",_rechargeArr[sender.tag-100].rechageId] ;}else{btn.backgroundColor = [UIColor colorWithRed:242.f/255.f green:242.f/255.f blue:242.f/255.f alpha:1];}}}- (IBAction)skipAgreement:(UIButton *)sender {WebViewController *vc = [[WebViewController alloc] init];vc.url = @"http://manage.mabaoxc.com/p/notify/getNotify?id=3";[self.navigationController pushViewController:vc animated:YES];}- (IBAction)pay:(UIButton *)sender {[CommonUtils showLoadingHudModelWithView:self.view handle:nil];NSString *url = [kBaseUrl stringByAppendingPathComponent:kMemberRecharge];NSString *SIGN = [CommonUtils getSign];NSString *AUTH = [Account shareAccount].user.auth;AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];[manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];[manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];[manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {//参数NSString *payment;if (_isALPay) {payment = @"1";}else{payment = @"2";}[formData appendPartWithFormData:[payment dataUsingEncoding:NSUTF8StringEncoding] name:@"payment"];[formData appendPartWithFormData:[_rechargeid dataUsingEncoding:NSUTF8StringEncoding] name:@"rechargeid"];} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {NSLog(@"%@",responseObject);[CommonUtils hideHudForView:self.view];NSString *status = responseObject[@"status"];NSString *msg = responseObject[@"msg"];if ([status integerValue] == 1) {// 验证成功if (_isALPay) {[self AliPay:responseObject];}else{[self WXPay:responseObject[@"data"]];}}else{[CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {NSLog(@"%@",error);[CommonUtils hideHudForView:self.view];[CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];}];}- (void)AliPay:(NSDictionary *)responseObject{//应用注册scheme,在AliSDKDemo-Info.plist定义URL typesNSString *appScheme = @"mengbei";// NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式NSString *orderString = responseObject[@"data"];// NOTE: 调用支付结果开始支付[[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {NSLog(@"reslut = %@",resultDic);NSString *statusCode = resultDic[@"resultStatus"];if ([statusCode isEqual:@"9000"]) {////关闭页面dispatch_async(dispatch_get_main_queue(), ^{[CommonUtils showTextHudModeWithInfo:@"充值成功" view:self.view stayTime:1.5];});}else{dispatch_async(dispatch_get_main_queue(), ^{[CommonUtils showTextHudModeWithInfo:@"支付失败" view:self.view stayTime:1.5];});}}];}- (void)WXPay:(NSDictionary *)responseObject{PayReq *request = [[PayReq alloc] init] ;request.partnerId = responseObject[@"partnerid"];request.prepayId= responseObject[@"prepayid"];request.package = @"Sign=WXPay";request.nonceStr= responseObject[@"noncestr"];request.timeStamp= [responseObject[@"timestamp"] intValue];request.sign= responseObject[@"sign"];BOOL success = [WXApi sendReq:request];}- (void)selectALPay{_ALSelect.image = [UIImage imageNamed:@"withdraw_success"];_WXSelect.image = [UIImage imageNamed:@"Unchecked"];_isALPay = YES;}- (void)selectWXPay{_ALSelect.image = [UIImage imageNamed:@"Unchecked"];_WXSelect.image = [UIImage imageNamed:@"withdraw_success"];_isALPay = NO;}- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];// Dispose of any resources that can be recreated.}