[关闭]
@xiasiwole 2018-05-24T11:26:08.000000Z 字数 136544 阅读 975

萌呗代码

萌呗


APPDelegate

  1. #pragma mark 禁止横屏
  2. - (UIInterfaceOrientationMask )application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
  3. {
  4. return UIInterfaceOrientationMaskPortrait;
  5. }
  6. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  7. // Override point for customization after application launch.
  8. //APP主window配置
  9. self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  10. self.window.backgroundColor = [UIColor whiteColor];
  11. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];
  12. UINavigationController *homeVc = [sb instantiateViewControllerWithIdentifier:@"homeNav"];
  13. self.window.rootViewController = homeVc;
  14. [self.window makeKeyAndVisible];
  15. //高德地图appkey配置
  16. [AMapServices sharedServices].apiKey = kMapApikey;
  17. //开始定位
  18. [[LocationManager sharedLocationManager] startLoction];
  19. //微信支付
  20. [WXApi registerApp:kWXAppId];
  21. //极光推送
  22. //notice: 3.0.0及以后版本注册可以这样写,也可以继续用之前的注册方式
  23. JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
  24. entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
  25. if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
  26. // 可以添加自定义categories
  27. // NSSet<UNNotificationCategory *> *categories for iOS10 or later
  28. // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
  29. }
  30. [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
  31. //如不需要使用IDFA,advertisingIdentifier 可为nil
  32. [JPUSHService setupWithOption:launchOptions appKey:kJPushAppkey
  33. channel:@"app store"
  34. apsForProduction:YES
  35. advertisingIdentifier:nil];
  36. // 获取自定义消息推送内容
  37. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  38. [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
  39. [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
  40. NSLog(@"resCode : %d,registrationID: %@",resCode,registrationID);
  41. if (registrationID) {
  42. [self sendRegistrationID:registrationID];
  43. }
  44. }];
  45. [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
  46. return YES;
  47. }
  48. - (void)sendRegistrationID:(NSString *)registrationID{
  49. NSString *url = [kBaseUrl stringByAppendingPathComponent:@"i/member/setJPush"];
  50. [CommonUtils sendPOST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  51. [formData appendPartWithFormData:[registrationID dataUsingEncoding:NSUTF8StringEncoding] name:@"clientid"];
  52. [formData appendPartWithFormData:[@"2" dataUsingEncoding:NSUTF8StringEncoding] name:@"clientos"];
  53. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  54. NSLog(@"%@",responseObject);
  55. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
  56. NSLog(@"%@",error);
  57. }];
  58. }
  59. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
  60. if ([url.description hasPrefix:@"wx"]) {
  61. return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
  62. }
  63. if ([url.host isEqualToString:@"safepay"]) {
  64. // 支付跳转支付宝钱包进行支付,处理支付结果
  65. // [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
  66. // }];
  67. }
  68. return YES;
  69. }
  70. // NOTE: 9.0以后使用新API接口
  71. - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
  72. {
  73. if ([url.description hasPrefix:@"wx"]) {
  74. return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
  75. }
  76. if ([url.host isEqualToString:@"safepay"]) {
  77. // 支付跳转支付宝钱包进行支付,处理支付结果
  78. // [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
  79. // NSLog(@"result4444 = %@",resultDic);
  80. // NSString *statusCode = resultDic[@"resultStatus"];
  81. //
  82. // }];
  83. }
  84. return YES;
  85. }
  86. //推送
  87. - (void)application:(UIApplication *)application
  88. didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  89. /// Required - 注册 DeviceToken
  90. [JPUSHService registerDeviceToken:deviceToken];
  91. }
  92. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  93. //Optional
  94. NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
  95. }
  96. #pragma mark- JPUSHRegisterDelegate
  97. //APNS推送(APP退出的时候)
  98. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  99. // 取得 APNs 标准信息内容
  100. NSDictionary *aps = [userInfo valueForKey:@"aps"];
  101. NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
  102. NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
  103. NSString *sound = [aps valueForKey:@"sound"]; //播放的声音
  104. // []
  105. // 取得Extras字段内容
  106. NSString *customizeField1 = [userInfo valueForKey:@"customizeExtras"]; //服务端中Extras字段,key是自己定义的
  107. NSLog(@"content =[%@], badge=[%d], sound=[%@], customize field =[%@]",content,badge,sound,customizeField1);
  108. // iOS 10 以下 Required
  109. [JPUSHService handleRemoteNotification:userInfo];
  110. }
  111. //iOS 7 Remote Notification
  112. - (void)application:(UIApplication *)application didReceiveRemoteNotification: (NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  113. NSLog(@"this is iOS7 Remote Notification");
  114. // iOS 10 以下 Required
  115. [JPUSHService handleRemoteNotification:userInfo];
  116. completionHandler(UIBackgroundFetchResultNewData);
  117. }
  118. #pragma mark- JPUSHRegisterDelegate // 2.1.9版新增JPUSHRegisterDelegate,需实现以下两个方法
  119. // iOS 10 Support
  120. - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
  121. // Required
  122. NSDictionary * userInfo = notification.request.content.userInfo;
  123. if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
  124. [JPUSHService handleRemoteNotification:userInfo];
  125. }
  126. else {
  127. // 本地通知
  128. }
  129. completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以选择设置
  130. }
  131. // iOS 10 Support
  132. - (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler: (void (^)())completionHandler {
  133. // Required
  134. NSDictionary * userInfo = response.notification.request.content.userInfo;
  135. if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
  136. [JPUSHService handleRemoteNotification:userInfo];
  137. }
  138. else {
  139. // 本地通知
  140. }
  141. completionHandler(); // 系统要求执行这个方法
  142. }
  143. //获取自定义消息推送内容(长连接 APP启动中)
  144. - (void)networkDidReceiveMessage:(NSNotification *)notification {
  145. NSDictionary * userInfo = [notification userInfo];
  146. NSString *content = [userInfo valueForKey:@"content"];
  147. NSString *messageID = [userInfo valueForKey:@"_j_msgid"];
  148. NSDictionary *extras = [userInfo valueForKey:@"extras"];
  149. NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的Extras附加字段,key是自己定义的
  150. // if ([LCBluetoothManager sharedManager].conectedState == ConnectedState) {
  151. // //蓝牙正在连接车子
  152. // }else{
  153. // [[NSNotificationCenter defaultCenter] postNotificationName:@"closeLockByNoti" object:nil userInfo:extras];
  154. // }
  155. NSLog(@"通知:%@",userInfo);
  156. }

HomeViewController

  1. #import "HomeViewController.h"
  2. /**
  3. 地图
  4. */
  5. #import "System.h"
  6. #import "SettingView.h"
  7. #import "UserTableViewController.h"
  8. #import "Service1ViewController.h"
  9. #import "Service2ViewController.h"
  10. #import "Service3ViewController.h"
  11. #import "Service4ViewController.h"
  12. #import "ScanViewController.h"
  13. #import "StyleDIY.h"
  14. #import "Account.h"
  15. #import "LoginViewController.h"
  16. #import "DepositViewController.h"
  17. #import <CoreBluetooth/CoreBluetooth.h>
  18. #import "CommonUtils.h"
  19. #import "WalletViewController.h"
  20. #import "Login.h"
  21. #import "AuthViewController.h"
  22. #import "Home.h"
  23. #import "BusinessArea.h"
  24. //高得地图
  25. #import "Map.h"
  26. #import <MAMapKit/MAMapKit.h>
  27. #import <AMapFoundationKit/AMapFoundationKit.h>
  28. #import <AMapLocationKit/AMapLocationKit.h>
  29. #import "CostViewController.h"
  30. #import "LCBluetoothManager.h"
  31. #import "LocationManager.h"
  32. #import "WebViewController.h"
  33. #import "MessageTableViewController.h"
  34. @interface HomeViewController ()<SettingViewDelegate,MAMapViewDelegate,CLLocationManagerDelegate,AMapGeoFenceManagerDelegate>
  35. //地理围栏
  36. @property (nonatomic,strong) AMapGeoFenceManager *geoFenceManager;
  37. @property (nonatomic,strong) MAMapView *mapView;
  38. @property (weak, nonatomic) IBOutlet UIView *mapBackView;
  39. @property (weak, nonatomic) IBOutlet UIButton *CurrentBtn;
  40. @property (weak, nonatomic) IBOutlet UIButton *settingBtn;
  41. @property (weak, nonatomic) IBOutlet UIButton *refreshBtn;
  42. @property (weak, nonatomic) IBOutlet UIButton *userBtn;
  43. @property (weak, nonatomic) IBOutlet UIButton *scanBtn;
  44. @property (nonatomic,strong) UIImageView *locationImage;
  45. @property (nonatomic,strong) SettingView *settingView;
  46. @property (nonatomic) BOOL showSettingView;
  47. @property (weak, nonatomic) IBOutlet UILabel *depositLabel;
  48. @property (weak, nonatomic) IBOutlet UIView *tipView;
  49. @property (weak, nonatomic) IBOutlet NSLayoutConstraint *topMargin;
  50. //商圈
  51. @property (nonatomic,strong) NSMutableArray <BusinessArea *> *areaArr;
  52. @property (weak, nonatomic) IBOutlet UILabel *titleLab;
  53. //用车
  54. @property (weak, nonatomic) IBOutlet UIView *useView;
  55. @property (weak, nonatomic) IBOutlet NSLayoutConstraint *useViewHeight;
  56. @property (weak, nonatomic) IBOutlet UILabel *time;
  57. @property (weak, nonatomic) IBOutlet UILabel *distance;
  58. @property (weak, nonatomic) IBOutlet UILabel *heat;
  59. @property (weak, nonatomic) IBOutlet UIButton *lockBtn;
  60. @property (weak, nonatomic) IBOutlet UILabel *lockNo;
  61. @property (weak, nonatomic) IBOutlet UILabel *cost;
  62. @property (nonatomic,strong) NSTimer *rentTimer;
  63. //蓝牙状态
  64. @property (nonatomic, strong) MAAnnotationView *userLocationAnnotationView;
  65. @end
  66. #define kUseViewHeight 160
  67. @implementation HomeViewController
  68. - (void)viewDidLoad {
  69. [super viewDidLoad];
  70. //初始化地图
  71. [self configMapView];
  72. //初始化地理围栏
  73. [self initGeoFenceManager];
  74. //其他视图设置
  75. [self setOtherView];
  76. //蓝牙检测
  77. [LCBluetoothManager sharedManager];
  78. //旧令牌获取新令牌
  79. if ([[Account shareAccount] isLogin]) {
  80. [self getAuth];
  81. }
  82. //获取商圈
  83. [self getBusinessArea];
  84. [self configUserView];
  85. [self getRent];
  86. [self requestMemberInfo];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(openSuccess) name:kOpenLockSuccess object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closeLock:) name:kCloseLock object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSkip:) name:@"closeLockByNoti" object:nil];
  90. [self drawColor];
  91. }
  92. -(void)viewDidAppear:(BOOL)animated{
  93. [super viewDidAppear:animated];
  94. _mapView.showsUserLocation = YES;
  95. // _mapView.userTrackingMode = MAUserTrackingModeFollowWithHeading;
  96. }
  97. -(void)viewWillAppear:(BOOL)animated{
  98. [super viewWillAppear:animated];
  99. self.navigationController.navigationBar.hidden = YES;
  100. if ([[Account shareAccount].user.hasdeposit integerValue] == 1) {
  101. _tipView.hidden = YES;
  102. }else{
  103. _tipView.hidden = NO;
  104. }
  105. }
  106. - (void)notificationSkip:(NSNotification *)noti{
  107. [self skipFee:noti.userInfo];
  108. }
  109. - (void)openSuccess{
  110. _useViewHeight.constant = kUseViewHeight;
  111. _useView.hidden = NO;
  112. [self getRent];
  113. }
  114. #pragma mark - 视图配置
  115. - (void)drawColor{
  116. CAGradientLayer *gradientLayer = [CAGradientLayer layer];
  117. UIColor *beginColor = [UIColor colorWithRed:210.f/255.f green:20/255.f blue:25.f/255.f alpha:1];
  118. UIColor *endColor = [UIColor colorWithRed:240.f/255.f green:130.f/255.f blue:45.f/255.f alpha:1];
  119. gradientLayer.colors = @[(__bridge id)beginColor.CGColor, (__bridge id)endColor.CGColor];
  120. gradientLayer.locations = @[@0.1,@1.0];
  121. gradientLayer.startPoint = CGPointMake(0, 0);
  122. gradientLayer.endPoint = CGPointMake(1.0, 0);
  123. gradientLayer.frame = _tipView.bounds;
  124. [self.tipView.layer addSublayer:gradientLayer];
  125. [self.tipView bringSubviewToFront:self.tipView.subviews.firstObject];
  126. [self.tipView bringSubviewToFront:_depositLabel];
  127. CAGradientLayer *gradientLayer2 = [CAGradientLayer layer];
  128. gradientLayer2.colors = @[(__bridge id)beginColor.CGColor, (__bridge id)endColor.CGColor];
  129. gradientLayer2.locations = @[@0.1,@1.0];
  130. gradientLayer2.startPoint = CGPointMake(0, 0);
  131. gradientLayer2.endPoint = CGPointMake(1, 0);
  132. gradientLayer2.frame = CGRectMake(0, 0, kScreenW, _scanBtn.bounds.size.height);
  133. // _scanBtn.bounds;
  134. [self.scanBtn.layer addSublayer:gradientLayer2];
  135. [self.scanBtn bringSubviewToFront:_scanBtn.imageView];
  136. // self.scanBtn.layer bri
  137. }
  138. - (void)configMapView{
  139. [AMapServices sharedServices].enableHTTPS = YES;
  140. _mapView = [[MAMapView alloc] initWithFrame:_mapBackView.bounds];
  141. [_mapBackView addSubview:_mapView];
  142. //显示定位小蓝点
  143. _mapView.showsUserLocation = YES;
  144. _mapView.userTrackingMode = MAUserTrackingModeFollow;
  145. _mapView.delegate = self;
  146. // self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  147. _mapView.zoomLevel = 17;
  148. _mapView.minZoomLevel = 10;
  149. _mapView.showsCompass = NO;
  150. // _mapView.rotateEnabled = NO;
  151. // _mapView.rotateCameraEnabled = NO;
  152. MAUserLocationRepresentation *r = [[MAUserLocationRepresentation alloc] init];
  153. r.showsAccuracyRing = NO;///精度圈是否显示,默认YES
  154. r.showsHeadingIndicator = YES;///是否显示方向指示(MAUserTrackingModeFollowWithHeading模式开启)。默认为YES
  155. r.fillColor = [UIColor redColor];///精度圈 填充颜色, 默认 kAccuracyCircleDefaultColor
  156. r.strokeColor = [UIColor blueColor];///精度圈 边线颜色, 默认 kAccuracyCircleDefaultColor
  157. r.lineWidth = 2;///精度圈 边线宽度,默认0
  158. r.enablePulseAnnimation = YES;///内部蓝色圆点是否使用律动效果, 默认YES
  159. // r.locationDotBgColor = [UIColor greenColor];///定位点背景色,不设置默认白色
  160. // r.locationDotFillColor = [UIColor grayColor];///定位点蓝色圆点颜色,不设置默认蓝色
  161. r.image = [UIImage imageNamed:@"userPosition"];
  162. [self.mapView updateUserLocationRepresentation:r];
  163. }
  164. - (void)setOtherView{
  165. [self.view bringSubviewToFront:_settingBtn];
  166. [self.view bringSubviewToFront:_CurrentBtn];
  167. [self.view bringSubviewToFront:_refreshBtn];
  168. [self.view bringSubviewToFront:_userBtn];
  169. [self.view bringSubviewToFront:_scanBtn];
  170. _scanBtn.layer.cornerRadius = 30;
  171. _scanBtn.clipsToBounds = YES;
  172. _userBtn.layer.cornerRadius = 20;
  173. _userBtn.clipsToBounds = YES;
  174. _settingBtn.layer.cornerRadius = 20;
  175. _settingBtn.clipsToBounds = YES;
  176. _CurrentBtn.layer.cornerRadius = 20;
  177. _CurrentBtn.clipsToBounds = YES;
  178. _settingView = [[NSBundle mainBundle] loadNibNamed:@"SettingView" owner:nil options:nil][0];
  179. _settingView.frame = CGRectMake(20, kScreenH-250, kScreenW-40,220 );
  180. [self.view addSubview:_settingView];
  181. _settingView.hidden = YES;
  182. _settingView.layer.cornerRadius = 20;
  183. _settingView.clipsToBounds = YES;
  184. _settingView.delegate = self;
  185. _locationImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"location_start"]];
  186. _locationImage.bounds = CGRectMake(0, 0, 20, 40);
  187. _locationImage.center = self.view.center;
  188. [self.view addSubview:_locationImage];
  189. [self.view bringSubviewToFront:_locationImage];
  190. //tipView
  191. _depositLabel.layer.cornerRadius = 10;
  192. _depositLabel.clipsToBounds = YES;
  193. [self.view bringSubviewToFront:_tipView];
  194. UITapGestureRecognizer *tapGestureRecognizer1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(skipDeposit)];
  195. [self.tipView addGestureRecognizer:tapGestureRecognizer1];
  196. self.tipView.userInteractionEnabled = YES;
  197. }
  198. //在地图上绘制点标记
  199. - (void)addPointToMapviewWithLatitude:(NSString *)latitude longitude:(NSString *)longitude{
  200. MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
  201. pointAnnotation.coordinate = CLLocationCoordinate2DMake([latitude doubleValue], [longitude doubleValue]);
  202. [_mapView addAnnotation:pointAnnotation];
  203. }
  204. - (void)configUserView{
  205. [_lockBtn.layer setBorderColor: [UIColor blackColor].CGColor];
  206. [_lockBtn.layer setBorderWidth:1];
  207. _lockBtn.layer.cornerRadius = 4;
  208. _lockBtn.clipsToBounds = YES;
  209. _useViewHeight.constant = 0;
  210. _useView.hidden = YES;
  211. _titleLab.hidden = YES;
  212. }
  213. - (void)updateUserView:(NSDictionary *)dic{
  214. //隐藏扫码按钮
  215. _scanBtn.hidden = YES;
  216. _titleLab.hidden = NO;
  217. _useViewHeight.constant = kUseViewHeight;
  218. _useView.hidden = NO;
  219. float time = [CommonUtils getDifSinceNowWithTimetamp:dic[@"createtime"]];
  220. float dif = time/1000/60;
  221. _time.text = [NSString stringWithFormat:@"%.f分",dif];
  222. _lockNo.text = [NSString stringWithFormat:@"正在用车:%@",dic[@"lockno"]];
  223. _cost.text = [NSString stringWithFormat:@"预计花费:%.f元",[dic[@"cost"] floatValue]/100];
  224. MAMapPoint point1 = MAMapPointForCoordinate(CLLocationCoordinate2DMake([LocationManager sharedLocationManager].latitude,[LocationManager sharedLocationManager].longitude));
  225. NSArray *temArr = [dic[@"rentposition"] componentsSeparatedByString:@","];
  226. MAMapPoint point2 = MAMapPointForCoordinate(CLLocationCoordinate2DMake([temArr[0] floatValue],[temArr[1] floatValue]));
  227. //2.计算距离
  228. CLLocationDistance distance = MAMetersBetweenMapPoints(point1,point2)/1000.f;
  229. _distance.text = [NSString stringWithFormat:@"%.2fkm",distance];
  230. _heat.text = [NSString stringWithFormat:@"%.2f大卡",distance *8];
  231. // _heat.text = dic[@""];
  232. }
  233. - (void)initGeoFenceManager{
  234. [AMapServices sharedServices].apiKey = kMapApikey;
  235. self.geoFenceManager = [[AMapGeoFenceManager alloc] init];
  236. self.geoFenceManager.delegate = self;
  237. self.geoFenceManager.activeAction = AMapGeoFenceActiveActionInside | AMapGeoFenceActiveActionOutside | AMapGeoFenceActiveActionStayed; //设置希望侦测的围栏触发行为,默认是侦测用户进入围栏的行为,即AMapGeoFenceActiveActionInside,这边设置为进入,离开,停留(在围栏内10分钟以上),都触发回调
  238. self.geoFenceManager.allowsBackgroundLocationUpdates = YES;
  239. }
  240. - (void)skipFee:(NSDictionary *)dic{
  241. [_rentTimer invalidate];
  242. _scanBtn.hidden = NO;
  243. _titleLab.hidden = YES;
  244. _rentTimer = nil;
  245. _useViewHeight.constant = 0;
  246. _useView.hidden = YES;
  247. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];
  248. CostViewController *vc = [sb instantiateViewControllerWithIdentifier:@"cost"];
  249. vc.fee = dic[@"fee"];
  250. vc.useTime = dic[@"useTime"];
  251. [self.navigationController pushViewController:vc animated:YES];
  252. }
  253. #pragma mark - 网络请求
  254. //获取车锁
  255. - (void)getLocksWithFenceId:(NSString *)fenceid{
  256. NSString *url = [kBaseUrl stringByAppendingPathComponent:kGetLocks];
  257. NSString *SIGN = [CommonUtils getSign];
  258. NSString *AUTH = [Account shareAccount].user.auth;
  259. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  260. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  261. [manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];
  262. [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  263. [formData appendPartWithFormData:[fenceid dataUsingEncoding:NSUTF8StringEncoding] name:@"fenceid"];
  264. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  265. NSLog(@"%@",responseObject);
  266. //绘制点标记
  267. NSString *status = responseObject[@"status"];
  268. if ([status integerValue] == 1) {
  269. for (NSDictionary *dic in responseObject[@"data"]) {
  270. [self addPointToMapviewWithLatitude:dic[@"latitude"] longitude:dic[@"longitude"]];
  271. }
  272. }
  273. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  274. NSLog(@"%@",error);
  275. }];
  276. }
  277. - (void)closeLock:(NSNotification *)noti{
  278. [[LCBluetoothManager sharedManager] cancelPeripheralConnection];
  279. [[LocationManager sharedLocationManager] stopSaveRoute];;
  280. NSString *url = [kBaseUrl stringByAppendingPathComponent:kReturnLock];
  281. NSString *SIGN = [CommonUtils getSign];
  282. NSString *AUTH = [Account shareAccount].user.auth;
  283. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  284. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  285. [manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];
  286. [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  287. //参数
  288. [formData appendPartWithFormData:[noti.userInfo[@"rentid"] dataUsingEncoding:NSUTF8StringEncoding] name:@"rentid"];
  289. [formData appendPartWithFormData:[noti.userInfo[@"lockno"] dataUsingEncoding:NSUTF8StringEncoding] name:@"lockno"];
  290. LocationManager *locationManager = [LocationManager sharedLocationManager];
  291. // 归还地点的坐标 经度,纬度
  292. NSString *returnposition = [NSString stringWithFormat:@"%f,%f",locationManager.latitude,locationManager.longitude];
  293. [formData appendPartWithFormData:[returnposition dataUsingEncoding:NSUTF8StringEncoding] name:@"returnposition"];
  294. // 行迹坐标集 经度,纬度
  295. NSString *tem = locationManager.route;
  296. NSLog(@"行迹坐标集 经度,纬度:%@",tem);
  297. if (tem != nil) {
  298. [formData appendPartWithFormData:[locationManager.route dataUsingEncoding:NSUTF8StringEncoding] name:@"route"];
  299. }
  300. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  301. [CommonUtils hideHudForView:self.view];
  302. NSLog(@"%@",responseObject);
  303. NSString *status = responseObject[@"status"];
  304. NSString *msg = responseObject[@"msg"];
  305. if ([status integerValue] == 1) {
  306. [self skipFee:responseObject[@"data"]];
  307. [[NSUserDefaults standardUserDefaults] setObject:nil forKey:kQuerykey];
  308. [[LCBluetoothManager sharedManager] cancelPeripheralConnection];
  309. }else{
  310. [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];
  311. }
  312. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  313. NSLog(@"%@",error);
  314. [CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];
  315. }];
  316. }
  317. //查询用户是否有未结束的租用
  318. - (void)getRent{
  319. NSString *url = [kBaseUrl stringByAppendingPathComponent:kGetRent];
  320. NSString *SIGN = [CommonUtils getSign];
  321. NSString *AUTH = [Account shareAccount].user.auth;
  322. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  323. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  324. [manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];
  325. [manager POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  326. NSLog(@"%@",responseObject);
  327. NSString *status = responseObject[@"status"];
  328. NSString *msg = responseObject[@"msg"];
  329. if ([status integerValue] == 1) {
  330. //更新userView
  331. [self updateUserView:responseObject[@"data"]];
  332. //锁信息赋给 LCBlueToothMnager;
  333. LCBluetoothManager *BTEManager = [LCBluetoothManager sharedManager];
  334. if (BTEManager.lockno == nil) {
  335. BTEManager.lockno = responseObject[@"data"][@"lockno"];
  336. BTEManager.rentid = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"id"]];
  337. }
  338. //判断蓝牙是否处于连接状态
  339. if (BTEManager.conectedState != ConnectedState) {
  340. BTEManager.isReconnected = YES;
  341. BTEManager.rentid = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"id"]];
  342. [BTEManager connectBTEWtihLockNo:responseObject[@"data"][@"lockno"]];
  343. }
  344. if (_rentTimer == nil) {
  345. _rentTimer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(invaliTimer) userInfo:nil repeats:YES];
  346. }
  347. }else{
  348. _useViewHeight.constant = 0;
  349. _useView.hidden = YES;;
  350. [_rentTimer invalidate];
  351. _rentTimer = nil;
  352. // [[LocationManager sharedLocationManager] stopSaveRote];
  353. }
  354. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  355. NSLog(@"%@",error);
  356. }];
  357. }
  358. - (void)invaliTimer{
  359. [self getRent];
  360. }
  361. //获取用户最新信息
  362. - (void)requestMemberInfo{
  363. NSString *url = [kBaseUrl stringByAppendingPathComponent:kGetInfo];
  364. NSString *SIGN = [CommonUtils getSign];
  365. NSString *AUTH = [Account shareAccount].user.auth;
  366. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  367. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  368. [manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];
  369. [manager POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  370. NSLog(@"%@",responseObject);
  371. [CommonUtils hideHudForView:self.view];
  372. NSString *status = responseObject[@"status"];
  373. NSString *msg = responseObject[@"msg"];
  374. // [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];
  375. if ([status integerValue] == 1) {
  376. [[Account shareAccount] saveUserInfo:responseObject[@"data"]];
  377. }
  378. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  379. NSLog(@"%@",error);
  380. [CommonUtils hideHudForView:self.view];
  381. [CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];
  382. }];
  383. }
  384. //旧令牌获取新令牌
  385. - (void)getAuth{
  386. NSString *url = [kBaseUrl stringByAppendingPathComponent:kGetAuth];
  387. NSString *SIGN = [CommonUtils getSign];
  388. NSString *AUTH = [Account shareAccount].user.auth;
  389. NSString *IMEI = [CommonUtils getDeviceUUID];
  390. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  391. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  392. [manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];
  393. [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  394. //参数
  395. [formData appendPartWithFormData:[IMEI dataUsingEncoding:NSUTF8StringEncoding] name:@"IMEI"];
  396. [formData appendPartWithFormData:[@"2" dataUsingEncoding:NSUTF8StringEncoding] name:@"client"];
  397. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  398. [CommonUtils hideHudForView:self.view];
  399. NSLog(@"%@",responseObject);
  400. NSString *status = responseObject[@"status"];
  401. NSString *msg = responseObject[@"msg"];
  402. if ([status integerValue] == 1) {
  403. //验证成功,保存用户数据,
  404. // [[Account shareAccount] saveUserInfo:responseObject[@"data"]];
  405. }else{
  406. [CommonUtils showTextHudModeWithInfo:@"登录过期,请重新登录" view:self.view stayTime:1.5];
  407. [[Account shareAccount] logout];
  408. }
  409. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  410. NSLog(@"%@",error);
  411. }];
  412. }
  413. //获取商圈
  414. - (void)getBusinessArea{
  415. NSString *url = [kBaseUrl stringByAppendingPathComponent:kGetBusinessArea];
  416. NSString *SIGN = [CommonUtils getSign];
  417. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  418. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  419. [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  420. NSString *city = [LocationManager sharedLocationManager].loctionInfo.city;
  421. if (city == nil) {
  422. [formData appendPartWithFormData:[@"武汉市" dataUsingEncoding:NSUTF8StringEncoding] name:@"cityName"];
  423. }else{
  424. [formData appendPartWithFormData:[city dataUsingEncoding:NSUTF8StringEncoding] name:@"cityName"];
  425. }
  426. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  427. NSLog(@"%@",responseObject);
  428. NSString *status = responseObject[@"status"];
  429. NSString *msg = responseObject[@"msg"];
  430. if ([status integerValue] == 1) {
  431. //保存商圈数据
  432. _areaArr = [NSMutableArray array];
  433. for (NSDictionary *dict in responseObject[@"data"]) {
  434. BusinessArea *area = [[BusinessArea alloc] initBusinessArea:dict];
  435. [_areaArr addObject:area];
  436. //创建围栏
  437. double latitude = [dict[@"latitude"] doubleValue];
  438. double longitude = [dict[@"longitude"] doubleValue];
  439. double radius = [dict[@"radius"] doubleValue];
  440. NSString *areaId = dict[@"id"];
  441. CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);
  442. [self.geoFenceManager addCircleRegionForMonitoringWithCenter:coordinate radius:radius customID:areaId];
  443. //构造圆
  444. MACircle *circle = [MACircle circleWithCenterCoordinate:coordinate radius:radius];
  445. //在地图上添加圆
  446. [_mapView addOverlay: circle];
  447. }
  448. }
  449. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  450. NSLog(@"%@",error);
  451. }];
  452. }
  453. #pragma mark - 懒加载
  454. #pragma mark - private
  455. - (IBAction)message:(UIButton *)sender {
  456. MessageTableViewController *vc = [[MessageTableViewController alloc] init];
  457. [self.navigationController pushViewController:vc animated:YES];
  458. }
  459. //关锁未结算计费
  460. - (IBAction)repair:(UIButton *)sender {
  461. [[LCBluetoothManager sharedManager] cancelPeripheralConnection];
  462. [[LocationManager sharedLocationManager] stopSaveRoute];
  463. NSString *url = [kBaseUrl stringByAppendingPathComponent:kRepair];
  464. [CommonUtils sendPOST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  465. //参数 必选:
  466. //锁编号
  467. [formData appendPartWithFormData:[[LCBluetoothManager sharedManager].lockno dataUsingEncoding:NSUTF8StringEncoding] name:@"lockId"];
  468. // 报修类型
  469. [formData appendPartWithFormData:[@"7" dataUsingEncoding:NSUTF8StringEncoding] name:@"repairId"];
  470. // 故障类型
  471. [formData appendPartWithFormData:[@"关锁未结算" dataUsingEncoding:NSUTF8StringEncoding] name:@"faultName"];
  472. // 归还地点
  473. NSString *returnposition = [NSString stringWithFormat:@"%f,%f",[LocationManager sharedLocationManager].latitude,[LocationManager sharedLocationManager].longitude];
  474. [formData appendPartWithFormData:[returnposition dataUsingEncoding:NSUTF8StringEncoding] name:@"returnposition"];
  475. //租赁id
  476. [formData appendPartWithFormData:[[LCBluetoothManager sharedManager].rentid dataUsingEncoding:NSUTF8StringEncoding] name:@"rentId"];
  477. [formData appendPartWithFormData:[@"" dataUsingEncoding:NSUTF8StringEncoding] name:@"problemDescription"];
  478. [formData appendPartWithFormData:[@"" dataUsingEncoding:NSUTF8StringEncoding] name:@"url"];
  479. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  480. NSLog(@"%@",responseObject);
  481. NSString *status = responseObject[@"status"];
  482. NSString *msg = responseObject[@"msg"];
  483. if ([status integerValue] == 1) {
  484. [self skipFee:responseObject[@"data"]];
  485. [[NSUserDefaults standardUserDefaults] setObject:nil forKey:kQuerykey];
  486. }else{
  487. [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];
  488. }
  489. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
  490. NSLog(@"%@",error);
  491. [CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];
  492. }];
  493. }
  494. //点击缴纳押金
  495. - (void)skipDeposit{
  496. if (![[Account shareAccount] isLogin]) {
  497. //跳转登录页面
  498. [self skipLogin];
  499. }else{
  500. //判断是否实名认证
  501. if ([[Account shareAccount].user.verified integerValue] == 0) {
  502. //跳转实名认证
  503. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Login" bundle:[NSBundle mainBundle]];
  504. AuthViewController *vc = [sb instantiateViewControllerWithIdentifier:@"auth"];
  505. [self.navigationController pushViewController:vc animated:YES];
  506. }else{
  507. //跳转缴纳押金
  508. [self skipRechargeDeposit];
  509. }
  510. }
  511. }
  512. - (void)skipLogin{
  513. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Login" bundle:[NSBundle mainBundle]];
  514. LoginViewController *loginVc = [sb instantiateViewControllerWithIdentifier:@"login"];
  515. [self.navigationController pushViewController:loginVc animated:YES];
  516. }
  517. - (void)skipRechargeDeposit{
  518. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Login" bundle:[NSBundle mainBundle]];
  519. DepositViewController *vc = [sb instantiateViewControllerWithIdentifier:@"deposit"];
  520. [self.navigationController pushViewController:vc animated:YES];
  521. }
  522. /**
  523. 回到地图当前位置
  524. */
  525. - (IBAction)setCurrent:(UIButton *)sender {
  526. if (![[Account shareAccount] isLogin]) {
  527. //跳转登录页面
  528. [self skipLogin];
  529. }else{
  530. _mapView.centerCoordinate = _mapView.userLocation.location.coordinate;
  531. }
  532. }
  533. /**
  534. 弹出信息反馈页面
  535. @param sender nil
  536. */
  537. - (IBAction)setting:(UIButton *)sender {
  538. if (![[Account shareAccount] isLogin]) {
  539. //跳转登录页面
  540. [self skipLogin];
  541. }else{
  542. _settingView.hidden = NO;
  543. [self.view bringSubviewToFront:_settingView];
  544. // UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];
  545. //
  546. // WebViewController *vc = [[WebViewController alloc] init];
  547. // vc.url = @"http://manage.mabaoxc.com/html/problems.html";
  548. // [self.navigationController pushViewController:vc animated:YES];
  549. }
  550. }
  551. /**
  552. 跳转个人中心
  553. @param sender nil
  554. */
  555. - (IBAction)skipUser:(UIButton *)sender {
  556. if (![[Account shareAccount] isLogin]) {
  557. //跳转登录页面
  558. [self skipLogin];
  559. }else{
  560. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"User" bundle:[NSBundle mainBundle]];
  561. UserTableViewController *userVC = [sb instantiateViewControllerWithIdentifier:@"user"];
  562. [self.navigationController pushViewController:userVC animated:YES];
  563. }
  564. }
  565. /**
  566. 刷新地图
  567. @param sender nil
  568. */
  569. - (IBAction)refreshMap:(UIButton *)sender {
  570. [_mapView reloadMap];
  571. }
  572. //扫码
  573. - (IBAction)scan:(UIButton *)sender {
  574. if (![[Account shareAccount] isLogin]) {
  575. //跳转登录页面
  576. [self skipLogin];
  577. }else if ([[Account shareAccount].user.hasdeposit floatValue] == 0){
  578. //未交押金 跳转缴纳押金页面
  579. [self skipDeposit];
  580. }
  581. else if ([[Account shareAccount].user.money floatValue] <0){
  582. //跳转充值页面
  583. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"User" bundle:[NSBundle mainBundle]];
  584. WalletViewController *vc = [sb instantiateViewControllerWithIdentifier:@"wallet"];
  585. [self.navigationController pushViewController:vc animated:YES];
  586. }
  587. // else if (![LCBluetoothManager isBlueOpen]){
  588. // //蓝牙未打开 提示用户开启蓝牙
  589. // [CommonUtils showAlertWithTitle:@"系统提示" alertMessage:@"检测您的蓝牙设备未开启,需要打开蓝牙才能扫码骑车" action1Title:@"去打开蓝牙" action1Stytle:UIAlertActionStyleDefault action1Handler:^(UIAlertAction *action) {
  590. // [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Bluetooth"]];
  591. // } action2Title:@"取消" action1Stytle:UIAlertActionStyleCancel action1Handler:^(UIAlertAction *action) {
  592. //
  593. // } presentVC:self];
  594. // }
  595. else{
  596. ScanViewController *vc = [[ScanViewController alloc] init];
  597. vc.style = [StyleDIY myStyle];
  598. vc.isOpenInterestRect = YES;
  599. vc.libraryType = SLT_Native;
  600. vc.scanCodeType = SCT_QRCode;
  601. [self.navigationController pushViewController:vc animated:YES];
  602. }
  603. }
  604. #pragma mark - SettingViewDelegate
  605. -(void)didSelectedService1{
  606. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];
  607. Service1ViewController *vc1 = [sb instantiateViewControllerWithIdentifier:@"service1"];
  608. [self.navigationController pushViewController:vc1 animated:YES];
  609. }
  610. -(void)didSelectedService2{
  611. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];
  612. Service2ViewController *vc2 = [sb instantiateViewControllerWithIdentifier:@"service2"];
  613. [self.navigationController pushViewController:vc2 animated:YES];
  614. }
  615. -(void)didSelectedService3{
  616. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];
  617. Service3ViewController *vc3 = [sb instantiateViewControllerWithIdentifier:@"service3"];
  618. [self.navigationController pushViewController:vc3 animated:YES];
  619. }
  620. -(void)didSelectedService4{
  621. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];
  622. Service4ViewController *vc3 = [sb instantiateViewControllerWithIdentifier:@"service4"];
  623. [self.navigationController pushViewController:vc3 animated:YES];
  624. }
  625. #pragma mark - MapDelegate
  626. //用户地理位置更新的时候
  627. -(void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{
  628. if (!updatingLocation && self.userLocationAnnotationView != nil)
  629. {
  630. [UIView animateWithDuration:0.1 animations:^{
  631. double degree = userLocation.heading.trueHeading - self.mapView.rotationDegree;
  632. self.userLocationAnnotationView.transform = CGAffineTransformMakeRotation(degree * M_PI / 180.f );
  633. }];
  634. }
  635. //记录轨迹
  636. }
  637. //地图的显示区域已经发生改变的时候调用
  638. - (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction{
  639. if (wasUserAction) {
  640. [UIView animateWithDuration:0.5 animations:^{
  641. _locationImage.center = CGPointMake(self.view.center.x, self.view.center.y-20);
  642. } completion:^(BOOL finished) {
  643. _locationImage.center = CGPointMake(self.view.center.x, self.view.center.y);
  644. }];
  645. }
  646. }
  647. - (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
  648. ;
  649. }
  650. //地图上绘制圆
  651. -(MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay{
  652. if ([overlay isKindOfClass:[MACircle class]])
  653. {
  654. MACircleRenderer *circleRenderer = [[MACircleRenderer alloc] initWithCircle:overlay];
  655. circleRenderer.lineWidth = 1.f;
  656. circleRenderer.strokeColor = [UIColor colorWithRed:126.f/255.f green:209.f/255.f blue:236.f/255.f alpha:0.4];
  657. circleRenderer.fillColor = [UIColor colorWithRed:126.f/255.f green:209.f/255.f blue:236.f/255.f alpha:0.4];
  658. return circleRenderer;
  659. }
  660. /* 自定义定位精度对应的MACircleView. */
  661. if (overlay == mapView.userLocationAccuracyCircle)
  662. {
  663. MACircleRenderer *accuracyCircleRenderer = [[MACircleRenderer alloc] initWithCircle:overlay];
  664. accuracyCircleRenderer.lineWidth = 2.f;
  665. accuracyCircleRenderer.strokeColor = [UIColor lightGrayColor];
  666. accuracyCircleRenderer.fillColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:.3];
  667. return accuracyCircleRenderer;
  668. }
  669. return nil;
  670. }
  671. //地理围栏
  672. - (void)amapGeoFenceManager:(AMapGeoFenceManager *)manager didAddRegionForMonitoringFinished:(NSArray<AMapGeoFenceRegion *> *)regions customID:(NSString *)customID error:(NSError *)error {
  673. if (error) {
  674. NSLog(@"创建失败 %@",error);
  675. } else {
  676. NSLog(@"创建成功");
  677. }
  678. }
  679. - (void)amapGeoFenceManager:(AMapGeoFenceManager *)manager didGeoFencesStatusChangedForRegion:(AMapGeoFenceRegion *)region customID:(NSString *)customID error:(NSError *)error {
  680. if (error) {
  681. NSLog(@"status changed error %@",error);
  682. }else{
  683. if (region.fenceStatus == AMapGeoFenceRegionStatusInside) {
  684. [self getLocksWithFenceId:customID];
  685. }
  686. }
  687. }
  688. //绘制点
  689. - (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
  690. {
  691. if ([annotation isKindOfClass:[MAPointAnnotation class]] && !([annotation isKindOfClass:[MAUserLocation class]]))
  692. {
  693. static NSString *reuseIndetifier = @"annotationReuseIndetifier";
  694. MAAnnotationView *annotationView = (MAAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
  695. if (annotationView == nil)
  696. {
  697. annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
  698. }
  699. annotationView.imageView.frame = CGRectMake(0, 0, 20, 20);
  700. annotationView.image = [UIImage imageNamed:@"logo_icon"];
  701. //设置中心点偏移,使得标注底部中间点成为经纬度对应点
  702. annotationView.centerOffset = CGPointMake(0, -18);
  703. return annotationView;
  704. }
  705. /* 自定义userLocation对应的annotationView. */
  706. if ([annotation isKindOfClass:[MAUserLocation class]])
  707. {
  708. static NSString *userLocationStyleReuseIndetifier = @"userLocationStyleReuseIndetifier";
  709. MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:userLocationStyleReuseIndetifier];
  710. if (annotationView == nil)
  711. {
  712. annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
  713. reuseIdentifier:userLocationStyleReuseIndetifier];
  714. }
  715. annotationView.image = [UIImage imageNamed:@"userPosition"];
  716. self.userLocationAnnotationView = annotationView;
  717. return annotationView;
  718. }
  719. return nil;
  720. }
  721. #pragma mark - CLLocationManagerDelegate
  722. -(void)centralManagerDidUpdateState:(CBCentralManager *)central
  723. {
  724. //第一次打开或者每次蓝牙状态改变都会调用这个函数
  725. if(central.state==CBCentralManagerStatePoweredOn)
  726. {
  727. NSLog(@"蓝牙设备开着");
  728. }
  729. else
  730. {
  731. [CommonUtils showTextHudModeWithInfo:@"蓝牙未打开" view:self.view stayTime:1.5];
  732. }
  733. }
  734. - (void)didReceiveMemoryWarning {
  735. [super didReceiveMemoryWarning];
  736. // Dispose of any resources that can be recreated.
  737. }
  738. -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
  739. if ([touches allObjects][0].view != _settingView) {
  740. _settingView.hidden = YES;
  741. _showSettingView = NO;
  742. }
  743. }

Service1ViewController

  1. - (void)viewDidLoad {
  2. [super viewDidLoad];
  3. [self drawColor];
  4. }
  5. -(void)viewWillAppear:(BOOL)animated{
  6. [super viewWillAppear:animated];
  7. [self setNav];
  8. if (_codeStr) {
  9. _code.text = _codeStr;
  10. }
  11. }
  12. - (void)setNav{
  13. self.navigationController.navigationBar.hidden = NO;
  14. self.title = @"开不了锁";
  15. UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
  16. left.image = [UIImage imageNamed:@"back"];
  17. left.tintColor = [UIColor blackColor];
  18. self.navigationItem.leftBarButtonItem = left;
  19. }
  20. - (void)drawColor{
  21. CAGradientLayer *gradientLayer = [CAGradientLayer layer];
  22. UIColor *beginColor = [UIColor colorWithRed:210.f/255.f green:20/255.f blue:25.f/255.f alpha:1];
  23. UIColor *endColor = [UIColor colorWithRed:240.f/255.f green:130.f/255.f blue:45.f/255.f alpha:1];
  24. gradientLayer.colors = @[(__bridge id)beginColor.CGColor, (__bridge id)endColor.CGColor];
  25. gradientLayer.locations = @[@0.1,@1.0];
  26. gradientLayer.startPoint = CGPointMake(0, 0);
  27. gradientLayer.endPoint = CGPointMake(1.0, 0);
  28. gradientLayer.frame = CGRectMake(0, 0, kScreenW, _sureBtn.bounds.size.height);
  29. [self.sureBtn.layer addSublayer:gradientLayer];
  30. _sureBtn.layer.cornerRadius = _sureBtn.bounds.size.height/2;
  31. _sureBtn.clipsToBounds = YES;
  32. [_code setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
  33. }
  34. - (void)close{
  35. [self.navigationController popViewControllerAnimated:YES];
  36. }
  37. - (IBAction)submit:(UIButton *)sender {
  38. [_comment resignFirstResponder];
  39. [_code resignFirstResponder];
  40. if (_code.text.length<8) {
  41. [CommonUtils showTextHudModeWithInfo:@"请输入正确的锁编号" view:self.view stayTime:1.5];
  42. }else{
  43. [CommonUtils showLoadingHudWithView:self.view text:nil];
  44. NSString *url = [kBaseUrl stringByAppendingPathComponent:kRepair];
  45. NSString *SIGN = [CommonUtils getSign];
  46. NSString *AUTH = [Account shareAccount].user.auth;
  47. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  48. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  49. [manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];
  50. [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  51. //参数 必选:
  52. [formData appendPartWithFormData:[_code.text dataUsingEncoding:NSUTF8StringEncoding] name:@"lockId"];
  53. [formData appendPartWithFormData:[@"1" dataUsingEncoding:NSUTF8StringEncoding] name:@"repairId"];
  54. [formData appendPartWithFormData:[@"开不了锁" dataUsingEncoding:NSUTF8StringEncoding] name:@"faultName"];
  55. //可选:
  56. [formData appendPartWithFormData:[_comment.text dataUsingEncoding:NSUTF8StringEncoding] name:@"problemDescription"];
  57. LocationManager *manager = [LocationManager sharedLocationManager];
  58. NSString *returnposition = [NSString stringWithFormat:@"%f,%f",manager.latitude,manager.longitude];
  59. [formData appendPartWithFormData:[returnposition dataUsingEncoding:NSUTF8StringEncoding] name:@"returnposition"];
  60. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  61. [CommonUtils hideHudForView:self.view];
  62. NSLog(@"%@",responseObject);
  63. NSString *status = responseObject[@"status"];
  64. NSString *msg = responseObject[@"msg"];
  65. [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];
  66. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  67. NSLog(@"%@",error);
  68. [CommonUtils hideHudForView:self.view];
  69. [CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];
  70. }];
  71. }
  72. }
  73. - (IBAction)scan:(UIButton *)sender {
  74. ScanViewController *vc = [[ScanViewController alloc] init];
  75. vc.style = [StyleDIY myStyle];
  76. vc.isOpenInterestRect = YES;
  77. vc.libraryType = SLT_Native;
  78. vc.scanCodeType = SCT_QRCode;
  79. vc.isInputCode = YES;
  80. [self.navigationController pushViewController:vc animated:YES];
  81. }
  82. -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
  83. [_comment resignFirstResponder];
  84. [_code resignFirstResponder];
  85. }
  86. - (void)didReceiveMemoryWarning {
  87. [super didReceiveMemoryWarning];
  88. // Dispose of any resources that can be recreated.
  89. }

Service2ViewController

  1. - (void)viewDidLoad {
  2. [super viewDidLoad];
  3. _selectImage.userInteractionEnabled = YES;
  4. UITapGestureRecognizer *tapGestureRecognizer1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selecteImage)];
  5. [self.selectImage addGestureRecognizer:tapGestureRecognizer1];
  6. _allQuestion = @[@"车太重,骑不动",@"二维码脱落",@"把套坏了",@"车铃丢了",@"踏板坏了",@"龙头歪斜",@"刹车失灵",@"其他"];
  7. _selectedQuestion = [NSMutableArray array];
  8. _selectIndexArr = [NSMutableArray array];
  9. [self drawColor];
  10. }
  11. -(void)viewDidAppear:(BOOL)animated{
  12. [super viewDidAppear:animated];
  13. _pickerVc = [[UIImagePickerController alloc] init];
  14. _pickerVc.delegate = self;
  15. _pickerVc.allowsEditing = YES;
  16. }
  17. -(void)viewWillAppear:(BOOL)animated{
  18. [super viewWillAppear:animated];
  19. [self setUpNav];
  20. if (_codeStr) {
  21. _code.text = _codeStr;
  22. }
  23. }
  24. - (void)setUpNav{
  25. self.navigationController.navigationBar.hidden = NO;
  26. self.title = @"故障上报";
  27. UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
  28. left.image = [UIImage imageNamed:@"back"];
  29. left.tintColor = [UIColor blackColor];
  30. self.navigationItem.leftBarButtonItem = left;
  31. }
  32. - (void)close{
  33. [self.navigationController popViewControllerAnimated:YES];
  34. }
  35. - (void)drawColor{
  36. CAGradientLayer *gradientLayer = [CAGradientLayer layer];
  37. UIColor *beginColor = [UIColor colorWithRed:210.f/255.f green:20/255.f blue:25.f/255.f alpha:1];
  38. UIColor *endColor = [UIColor colorWithRed:240.f/255.f green:130.f/255.f blue:45.f/255.f alpha:1];
  39. gradientLayer.colors = @[(__bridge id)beginColor.CGColor, (__bridge id)endColor.CGColor];
  40. gradientLayer.locations = @[@0.1,@1.0];
  41. gradientLayer.startPoint = CGPointMake(0, 0);
  42. gradientLayer.endPoint = CGPointMake(1.0, 0);
  43. gradientLayer.frame = CGRectMake(0, 0, kScreenW, _sureBtn.bounds.size.height);
  44. [self.sureBtn.layer addSublayer:gradientLayer];
  45. _sureBtn.layer.cornerRadius = _sureBtn.bounds.size.height/2;
  46. _sureBtn.clipsToBounds = YES;
  47. [_code setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
  48. }
  49. - (IBAction)scan:(UIButton *)sender {
  50. ScanViewController *vc = [[ScanViewController alloc] init];
  51. vc.style = [StyleDIY myStyle];
  52. vc.isOpenInterestRect = YES;
  53. vc.libraryType = SLT_Native;
  54. vc.scanCodeType = SCT_QRCode;
  55. vc.isInputCode = YES;
  56. [self.navigationController pushViewController:vc animated:YES];
  57. }
  58. - (IBAction)clickQuestion:(UIButton *)sender {
  59. NSString *tagStr = [NSString stringWithFormat:@"%ld",(long)sender.tag];
  60. if ([_selectIndexArr containsObject:tagStr]) {
  61. [sender setImage:[UIImage imageNamed:@"ic_unselet"] forState:UIControlStateNormal];
  62. [_selectIndexArr removeObject:tagStr];
  63. [_selectedQuestion removeObject:_allQuestion[sender.tag-100]];
  64. }else{
  65. [sender setImage:[UIImage imageNamed:@"ic_selected1"] forState:UIControlStateNormal];
  66. [_selectIndexArr addObject:tagStr];
  67. [_selectedQuestion addObject:_allQuestion[sender.tag-100]];
  68. }
  69. NSLog(@"%@",[_selectedQuestion componentsJoinedByString:@","]);
  70. }
  71. - (void)selecteImage{
  72. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  73. UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  74. _pickerVc.sourceType = UIImagePickerControllerSourceTypeCamera;
  75. [self presentViewController:_pickerVc animated:YES completion:nil];
  76. }];
  77. [alertVC addAction:cameraAction];
  78. UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  79. _pickerVc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  80. [self presentViewController:_pickerVc animated:YES completion:nil];
  81. }];
  82. [alertVC addAction:albumAction];
  83. UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  84. }];
  85. [alertVC addAction:cancleAction];
  86. [self presentViewController:alertVC animated:YES completion:nil];
  87. }
  88. - (IBAction)submit:(UIButton *)sender {
  89. [_comment resignFirstResponder];
  90. [_code resignFirstResponder];
  91. if (_code.text.length<8) {
  92. [CommonUtils showTextHudModeWithInfo:@"请输入正确的锁编号" view:self.view stayTime:1.5];
  93. }else if (_selectedQuestion.count == 0){
  94. [CommonUtils showTextHudModeWithInfo:@"请至少选择一个故障原因" view:self.view stayTime:1.5];
  95. }
  96. else{
  97. [CommonUtils showLoadingHudWithView:self.view text:nil];
  98. NSString *url = [kBaseUrl stringByAppendingPathComponent:kRepair];
  99. NSString *SIGN = [CommonUtils getSign];
  100. NSString *AUTH = [Account shareAccount].user.auth;
  101. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  102. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  103. [manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];
  104. [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  105. //参数
  106. [formData appendPartWithFormData:[_code.text dataUsingEncoding:NSUTF8StringEncoding] name:@"lockId"];
  107. [formData appendPartWithFormData:[@"2" dataUsingEncoding:NSUTF8StringEncoding] name:@"repairId"];
  108. [formData appendPartWithFormData:[[_selectedQuestion componentsJoinedByString:@","] dataUsingEncoding:NSUTF8StringEncoding] name:@"faultName"];
  109. [formData appendPartWithFormData:[_comment.text dataUsingEncoding:NSUTF8StringEncoding] name:@"problemDescription"];
  110. if (_image) {
  111. [formData appendPartWithFormData:UIImageJPEGRepresentation(_image, 0.2) name:@"url"];
  112. }
  113. LocationManager *manager = [LocationManager sharedLocationManager];
  114. NSString *returnposition = [NSString stringWithFormat:@"%f,%f",manager.latitude,manager.longitude];
  115. [formData appendPartWithFormData:[returnposition dataUsingEncoding:NSUTF8StringEncoding] name:@"returnposition"];
  116. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  117. [CommonUtils hideHudForView:self.view];
  118. NSLog(@"%@",responseObject);
  119. NSString *msg = responseObject[@"msg"];
  120. [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];
  121. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  122. NSLog(@"%@",error);
  123. [CommonUtils hideHudForView:self.view];
  124. [CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];
  125. }];
  126. }
  127. }
  128. -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
  129. [_comment resignFirstResponder];
  130. [_code resignFirstResponder];
  131. }
  132. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
  133. NSLog(@"%@",info);
  134. _selectImage.image = info[@"UIImagePickerControllerEditedImage"];
  135. _image = info[@"UIImagePickerControllerEditedImage"];
  136. [self dismissViewControllerAnimated:YES completion:nil];
  137. }
  138. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
  139. [self dismissViewControllerAnimated:YES completion:nil];
  140. }

Service3ViewController

  1. #import "Service3ViewController.h"
  2. #import "CommonUtils.h"
  3. #import "Account.h"
  4. #import "ScanViewController.h"
  5. #import "StyleDIY.h"
  6. #import "Home.h"
  7. #import "LocationManager.h"
  8. @interface Service3ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
  9. @property (weak, nonatomic) IBOutlet UIImageView *selectImage;
  10. @property (weak, nonatomic) IBOutlet UITextField *code;
  11. @property (weak, nonatomic) IBOutlet UITextView *comment;
  12. @property (nonatomic,strong) UIImagePickerController *pickerVc;
  13. @property (nonatomic,strong) UIImage *image;
  14. @property (weak, nonatomic) IBOutlet UIButton *sureBtn;
  15. @end
  16. @implementation Service3ViewController
  17. - (void)viewDidLoad {
  18. [super viewDidLoad];
  19. _selectImage.userInteractionEnabled = YES;
  20. UITapGestureRecognizer *tapGestureRecognizer1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selecteImage)];
  21. [self.selectImage addGestureRecognizer:tapGestureRecognizer1];
  22. [self drawColor];
  23. }
  24. -(void)viewDidAppear:(BOOL)animated{
  25. [super viewDidAppear:animated];
  26. _pickerVc = [[UIImagePickerController alloc] init];
  27. _pickerVc.delegate = self;
  28. _pickerVc.allowsEditing = YES;
  29. }
  30. - (void)viewWillAppear:(BOOL)animated{
  31. [super viewWillAppear:animated];
  32. [self setUpNav];
  33. if (_codeStr) {
  34. _code.text = _codeStr;
  35. }
  36. }
  37. - (void)drawColor{
  38. CAGradientLayer *gradientLayer = [CAGradientLayer layer];
  39. UIColor *beginColor = [UIColor colorWithRed:210.f/255.f green:20/255.f blue:25.f/255.f alpha:1];
  40. UIColor *endColor = [UIColor colorWithRed:240.f/255.f green:130.f/255.f blue:45.f/255.f alpha:1];
  41. gradientLayer.colors = @[(__bridge id)beginColor.CGColor, (__bridge id)endColor.CGColor];
  42. gradientLayer.locations = @[@0.1,@1.0];
  43. gradientLayer.startPoint = CGPointMake(0, 0);
  44. gradientLayer.endPoint = CGPointMake(1.0, 0);
  45. gradientLayer.frame = CGRectMake(0, 0, kScreenW, _sureBtn.bounds.size.height);
  46. [self.sureBtn.layer addSublayer:gradientLayer];
  47. _sureBtn.layer.cornerRadius = _sureBtn.bounds.size.height/2;
  48. _sureBtn.clipsToBounds = YES;
  49. [_code setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
  50. }
  51. - (void)setUpNav{
  52. self.navigationController.navigationBar.hidden = NO;
  53. self.title = @"举报违停";
  54. UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
  55. left.image = [UIImage imageNamed:@"back"];
  56. left.tintColor = [UIColor blackColor];
  57. self.navigationItem.leftBarButtonItem = left;
  58. }
  59. - (void)close{
  60. [self.navigationController popViewControllerAnimated:YES];
  61. }
  62. - (IBAction)submit:(UIButton *)sender {
  63. [_comment resignFirstResponder];
  64. [_code resignFirstResponder];
  65. if (_code.text.length<8) {
  66. [CommonUtils showTextHudModeWithInfo:@"请输入正确的锁编号" view:self.view stayTime:1.5];
  67. }else{
  68. [CommonUtils showLoadingHudWithView:self.view text:nil];
  69. NSString *url = [kBaseUrl stringByAppendingPathComponent:kRepair];
  70. NSString *SIGN = [CommonUtils getSign];
  71. NSString *AUTH = [Account shareAccount].user.auth;
  72. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  73. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  74. [manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];
  75. [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  76. //参数
  77. [formData appendPartWithFormData:[_code.text dataUsingEncoding:NSUTF8StringEncoding] name:@"lockId"];
  78. [formData appendPartWithFormData:[@"3" dataUsingEncoding:NSUTF8StringEncoding] name:@"repairId"];
  79. [formData appendPartWithFormData:[@"举报违停" dataUsingEncoding:NSUTF8StringEncoding] name:@"faultName"];
  80. [formData appendPartWithFormData:[_comment.text dataUsingEncoding:NSUTF8StringEncoding] name:@"problemDescription"];
  81. LocationManager *manager = [LocationManager sharedLocationManager];
  82. NSString *returnposition = [NSString stringWithFormat:@"%f,%f",manager.latitude,manager.longitude];
  83. [formData appendPartWithFormData:[returnposition dataUsingEncoding:NSUTF8StringEncoding] name:@"returnposition"];
  84. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  85. [CommonUtils hideHudForView:self.view];
  86. NSLog(@"%@",responseObject);
  87. NSString *status = responseObject[@"status"];
  88. NSString *msg = responseObject[@"msg"];
  89. [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];
  90. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  91. NSLog(@"%@",error);
  92. [CommonUtils hideHudForView:self.view];
  93. [CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];
  94. }];
  95. }
  96. }
  97. - (IBAction)scan:(UIButton *)sender {
  98. ScanViewController *vc = [[ScanViewController alloc] init];
  99. vc.style = [StyleDIY myStyle];
  100. vc.isOpenInterestRect = YES;
  101. vc.libraryType = SLT_Native;
  102. vc.scanCodeType = SCT_QRCode;
  103. vc.isInputCode = YES;
  104. [self.navigationController pushViewController:vc animated:YES];
  105. }
  106. - (void)selecteImage{
  107. // _pickerVc = [[UIImagePickerController alloc] init];
  108. // _pickerVc.delegate = self;
  109. // _pickerVc.allowsEditing = YES;
  110. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  111. UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  112. _pickerVc.sourceType = UIImagePickerControllerSourceTypeCamera;
  113. [self presentViewController:_pickerVc animated:YES completion:nil];
  114. }];
  115. [alertVC addAction:cameraAction];
  116. UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  117. _pickerVc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  118. [self presentViewController:_pickerVc animated:YES completion:nil];
  119. }];
  120. [alertVC addAction:albumAction];
  121. UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  122. }];
  123. [alertVC addAction:cancleAction];
  124. [self presentViewController:alertVC animated:YES completion:nil];
  125. }
  126. -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
  127. [_comment resignFirstResponder];
  128. [_code resignFirstResponder];
  129. }
  130. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
  131. _selectImage.image = info[@"UIImagePickerControllerEditedImage"];
  132. _image = info[@"UIImagePickerControllerEditedImage"];
  133. [self dismissViewControllerAnimated:YES completion:nil];
  134. }
  135. - (void)didReceiveMemoryWarning {
  136. [super didReceiveMemoryWarning];
  137. // Dispose of any resources that can be recreated.
  138. }

Service4ViewController

  1. #import "Service4ViewController.h"
  2. #import "CommonUtils.h"
  3. #import "Account.h"
  4. #import "ScanViewController.h"
  5. #import "StyleDIY.h"
  6. #import "Home.h"
  7. #import "LocationManager.h"
  8. @interface Service4ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
  9. @property (weak, nonatomic) IBOutlet UIImageView *selectImage;
  10. @property (weak, nonatomic) IBOutlet UITextField *code;
  11. @property (nonatomic,strong) UIImagePickerController *pickerVc;
  12. @property (weak, nonatomic) IBOutlet UITextView *comment;
  13. @property (nonatomic,strong) UIImage *image;
  14. @property (weak, nonatomic) IBOutlet UIButton *sureBtn;
  15. @end
  16. @implementation Service4ViewController
  17. - (void)viewDidLoad {
  18. [super viewDidLoad];
  19. _selectImage.userInteractionEnabled = YES;
  20. UITapGestureRecognizer *tapGestureRecognizer1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selecteImage)];
  21. [self.selectImage addGestureRecognizer:tapGestureRecognizer1];
  22. [self drawColor];
  23. }
  24. -(void)viewDidAppear:(BOOL)animated{
  25. [super viewDidAppear:animated];
  26. _pickerVc = [[UIImagePickerController alloc] init];
  27. _pickerVc.delegate = self;
  28. _pickerVc.allowsEditing = YES;
  29. }
  30. - (void)viewWillAppear:(BOOL)animated{
  31. [super viewWillAppear:animated];
  32. [self setUpNav];
  33. if (_codeStr) {
  34. _code.text = _codeStr;
  35. }
  36. }
  37. - (void)drawColor{
  38. CAGradientLayer *gradientLayer = [CAGradientLayer layer];
  39. UIColor *beginColor = [UIColor colorWithRed:210.f/255.f green:20/255.f blue:25.f/255.f alpha:1];
  40. UIColor *endColor = [UIColor colorWithRed:240.f/255.f green:130.f/255.f blue:45.f/255.f alpha:1];
  41. gradientLayer.colors = @[(__bridge id)beginColor.CGColor, (__bridge id)endColor.CGColor];
  42. gradientLayer.locations = @[@0.1,@1.0];
  43. gradientLayer.startPoint = CGPointMake(0, 0);
  44. gradientLayer.endPoint = CGPointMake(1.0, 0);
  45. gradientLayer.frame = CGRectMake(0, 0, kScreenW, _sureBtn.bounds.size.height);
  46. [self.sureBtn.layer addSublayer:gradientLayer];
  47. _sureBtn.layer.cornerRadius = _sureBtn.bounds.size.height/2;
  48. _sureBtn.clipsToBounds = YES;
  49. [_code setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
  50. }
  51. - (void)setUpNav{
  52. self.navigationController.navigationBar.hidden = NO;
  53. self.title = @"清洁维护";
  54. UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
  55. left.image = [UIImage imageNamed:@"back"];
  56. left.tintColor = [UIColor blackColor];
  57. self.navigationItem.leftBarButtonItem = left;
  58. }
  59. - (void)close{
  60. [self.navigationController popViewControllerAnimated:YES];
  61. }
  62. - (void)selecteImage{
  63. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  64. UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  65. _pickerVc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  66. [self presentViewController:_pickerVc animated:YES completion:nil];
  67. }];
  68. [alertVC addAction:cameraAction];
  69. UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  70. _pickerVc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  71. [self presentViewController:_pickerVc animated:YES completion:nil];
  72. }];
  73. [alertVC addAction:albumAction];
  74. UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  75. }];
  76. [alertVC addAction:cancleAction];
  77. [self presentViewController:alertVC animated:YES completion:nil];
  78. }
  79. - (IBAction)scan:(UIButton *)sender {
  80. ScanViewController *vc = [[ScanViewController alloc] init];
  81. vc.style = [StyleDIY myStyle];
  82. vc.isOpenInterestRect = YES;
  83. vc.libraryType = SLT_Native;
  84. vc.scanCodeType = SCT_QRCode;
  85. vc.isInputCode = YES;
  86. [self.navigationController pushViewController:vc animated:YES];
  87. }
  88. - (IBAction)submit:(id)sender {
  89. [_comment resignFirstResponder];
  90. [_code resignFirstResponder];
  91. if (_code.text.length<8) {
  92. [CommonUtils showTextHudModeWithInfo:@"请输入正确的锁编号" view:self.view stayTime:1.5];
  93. }else{
  94. [CommonUtils showLoadingHudWithView:self.view text:nil];
  95. NSString *url = [kBaseUrl stringByAppendingPathComponent:kRepair];
  96. NSString *SIGN = [CommonUtils getSign];
  97. NSString *AUTH = [Account shareAccount].user.auth;
  98. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  99. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  100. [manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];
  101. [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  102. //参数
  103. [formData appendPartWithFormData:[_code.text dataUsingEncoding:NSUTF8StringEncoding] name:@"lockId"];
  104. [formData appendPartWithFormData:[@"4" dataUsingEncoding:NSUTF8StringEncoding] name:@"repairId"];
  105. [formData appendPartWithFormData:[@"清洁维护" dataUsingEncoding:NSUTF8StringEncoding] name:@"faultName"];
  106. [formData appendPartWithFormData:[_comment.text dataUsingEncoding:NSUTF8StringEncoding] name:@"problemDescription"];
  107. LocationManager *manager = [LocationManager sharedLocationManager];
  108. NSString *returnposition = [NSString stringWithFormat:@"%f,%f",manager.latitude,manager.longitude];
  109. [formData appendPartWithFormData:[returnposition dataUsingEncoding:NSUTF8StringEncoding] name:@"returnposition"];
  110. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  111. [CommonUtils hideHudForView:self.view];
  112. NSLog(@"%@",responseObject);
  113. NSString *msg = responseObject[@"msg"];
  114. [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];
  115. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  116. NSLog(@"%@",error);
  117. [CommonUtils hideHudForView:self.view];
  118. [CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];
  119. }];
  120. }
  121. }
  122. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
  123. _selectImage.image = info[@"UIImagePickerControllerEditedImage"];
  124. _image = info[@"UIImagePickerControllerEditedImage"];
  125. [self dismissViewControllerAnimated:YES completion:nil];
  126. }
  127. -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
  128. [_comment resignFirstResponder];
  129. [_code resignFirstResponder];
  130. }

ScanViewController

  1. #import "ScanViewController.h"
  2. #import "ScanBottomView.h"
  3. #import "InputCodeViewController.h"
  4. #import <CoreBluetooth/CoreBluetooth.h>
  5. #import "Home.h"
  6. #import "CommonUtils.h"
  7. #import "Account.h"
  8. #import "LCBluetoothManager.h"
  9. @interface ScanViewController ()
  10. @property (nonatomic,strong) ScanBottomView *bottomView;
  11. @property (nonatomic,strong) UILabel *tiplabel;
  12. @property (nonatomic,strong) UIButton *closeBtn;
  13. @property (nonatomic,strong) CBCentralManager *centralManager;
  14. @property (nonatomic,strong) CBPeripheralManager *peripheralManager;
  15. @property (nonatomic,strong) CBPeripheral *peripheral;
  16. @property (nonatomic,strong) NSString *secretkey;
  17. @property (nonatomic,strong) CBCharacteristic *characteristic;
  18. @property (nonatomic,strong) NSString *lockNo;
  19. @property (nonatomic) BOOL isBluetoothOpen;
  20. @end
  21. #define SERVICES_UUID @"1960"
  22. #define WRITE_UUID @"2BB1"
  23. #define READ_UUID @"2BB2"
  24. @implementation ScanViewController
  25. - (void)viewDidLoad {
  26. [super viewDidLoad];
  27. if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
  28. self.edgesForExtendedLayout = UIRectEdgeNone;
  29. }
  30. self.view.backgroundColor = [UIColor blackColor];
  31. self.navigationController.navigationBar.hidden = YES;
  32. //注册通知
  33. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(openSuccess) name:kOpenLockSuccess object:nil];
  34. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(openFailed) name:kOpenLockFailed object:nil];
  35. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopScan) name:kStopScap object:nil];
  36. _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
  37. }
  38. -(void)openSuccess{
  39. [CommonUtils hideHudForView:self.view];
  40. [self.navigationController popViewControllerAnimated:YES];
  41. }
  42. -(void)openFailed{
  43. [CommonUtils hideHudForView:self.view];
  44. [CommonUtils showTextHudModeWithInfo:@"开锁失败" view:self.view stayTime:1.5];
  45. [self reStartDevice];
  46. }
  47. - (void)stopScan{
  48. [CommonUtils hideHudForView:self.view];
  49. // [CommonUtils showTextHudModeWithInfo:@"扫描不到可用的蓝牙信息" view:self.view stayTime:1.5];
  50. [self reStartDevice];
  51. }
  52. -(void)viewWillAppear:(BOOL)animated{
  53. [super viewWillAppear:animated];
  54. self.navigationController.navigationBar.hidden = YES;
  55. if (_codeStr) {
  56. //手动输入编码,连接蓝牙;
  57. [self requestOpenLock:_codeStr];
  58. }
  59. }
  60. -(void)viewDidAppear:(BOOL)animated{
  61. [super viewDidAppear:animated];
  62. [self setUpScanView];
  63. }
  64. - (void)closePage{
  65. [self.navigationController popViewControllerAnimated:YES];
  66. }
  67. - (void)setUpScanView{
  68. //底部视图
  69. if (!_bottomView ) {
  70. _bottomView = [[NSBundle mainBundle] loadNibNamed:@"ScanBottomView" owner:nil options:nil][0];
  71. [self.view addSubview:_bottomView];
  72. _bottomView.frame = CGRectMake(0, CGRectGetMaxY(self.view.frame)-120, CGRectGetWidth(self.view.frame), 100);
  73. [self.view bringSubviewToFront:_bottomView];
  74. [_bottomView.input addTarget:self action:@selector(inputCode) forControlEvents:UIControlEventTouchUpInside];
  75. [_bottomView.flash addTarget:self action:@selector(openFlash) forControlEvents:UIControlEventTouchDown];
  76. }
  77. //提示文字
  78. if (!_tiplabel) {
  79. _tiplabel = [[UILabel alloc] init];
  80. _tiplabel.bounds = CGRectMake(0, 0, 145, 60);
  81. _tiplabel.center = CGPointMake(CGRectGetWidth(self.view.frame)/2, 100);
  82. _tiplabel.textAlignment = NSTextAlignmentCenter;
  83. _tiplabel.numberOfLines = 0;
  84. _tiplabel.font = [UIFont systemFontOfSize:15];
  85. _tiplabel.text = @"将取景框对准二维码即可自动扫描";
  86. _tiplabel.textColor = [UIColor whiteColor];
  87. [self.view addSubview:_tiplabel];
  88. }
  89. //返回按钮
  90. if (!_closeBtn) {
  91. _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  92. [_closeBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
  93. _closeBtn.frame = CGRectMake(0, 16, 60, 60);
  94. [_closeBtn addTarget:self action:@selector(closePage) forControlEvents:UIControlEventTouchUpInside];
  95. // _closeBtn.tintColor = [UIColor redColor];
  96. //// _closeB
  97. [self.view addSubview:_closeBtn];
  98. [self.view bringSubviewToFront:_closeBtn];
  99. }
  100. }
  101. - (void)inputCode{
  102. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];
  103. InputCodeViewController *vc = [sb instantiateViewControllerWithIdentifier:@"InputCodeVc"];
  104. vc.isInputCode = _isInputCode;
  105. [self.navigationController pushViewController:vc animated:YES];
  106. }
  107. - (void)openFlash{
  108. [self openOrCloseFlash];
  109. if (self.isOpenFlash) {
  110. [_bottomView.flash setImage:[UIImage imageNamed:@"手电筒2"] forState:UIControlStateNormal];
  111. }else{
  112. [_bottomView.flash setImage:[UIImage imageNamed:@"手电筒"] forState:UIControlStateNormal];
  113. }
  114. }
  115. - (void)scanResultWithArray:(NSArray<LBXScanResult*>*)array{
  116. if (!array || array.count < 1)
  117. //二维码的内容格式: http://locks.mabaoxc.com?lockno=72000049
  118. {
  119. return;
  120. }
  121. NSString *temStr = array[0].strScanned;
  122. if ([temStr hasPrefix:@"http://locks.mabaoxc.com?lockno"]) {
  123. NSString *code = [temStr componentsSeparatedByString:@"="].lastObject;
  124. _lockNo = code;
  125. if (_isInputCode) {
  126. NSArray *vcArr = self.navigationController.viewControllers;
  127. UIViewController *vc = vcArr[vcArr.count-2];
  128. [vc setValue:code forKey:@"codeStr"];
  129. [self.navigationController popViewControllerAnimated:YES];
  130. }
  131. else{
  132. if (_isBluetoothOpen) {
  133. [self requestOpenLock:code];
  134. }else{
  135. [CommonUtils showTextHudModeWithInfo:@"请打开蓝牙" view:self.view stayTime:1.5];
  136. }
  137. }
  138. }else{
  139. UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"提示" message:temStr preferredStyle:UIAlertControllerStyleAlert];
  140. UIAlertAction *act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
  141. [vc addAction:act];
  142. [self presentViewController:vc animated:YES completion:nil];
  143. }
  144. }
  145. #pragma mark - 网络请求
  146. - (void)requestOpenLock:(NSString *)str{
  147. [CommonUtils showLoadingHudWithView:self.view text:@"正在开锁中..."];
  148. NSString *url = [kBaseUrl stringByAppendingPathComponent:kOpenLock];
  149. NSString *SIGN = [CommonUtils getSign];
  150. NSString *AUTH = [Account shareAccount].user.auth;
  151. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  152. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  153. [manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];
  154. [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  155. //@"72000049"
  156. [formData appendPartWithFormData:[str dataUsingEncoding:NSUTF8StringEncoding] name:@"lockno"];
  157. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  158. NSLog(@"%@",responseObject);
  159. NSString *msg = responseObject[@"msg"];
  160. NSString *status = responseObject[@"status"];
  161. if ([status integerValue] == 1) {
  162. LCBluetoothManager *manager = [LCBluetoothManager sharedManager];
  163. [[NSUserDefaults standardUserDefaults] setObject:responseObject[@"data"][@"querykey"] forKey:kQuerykey];
  164. manager.secretkey = responseObject[@"data"][@"lockkey"];
  165. manager.rentid = responseObject[@"data"][@"rentid"];
  166. manager.rentposition = @"30.591498,114.219142";
  167. manager.scanView = self.view;
  168. manager.lockno = _lockNo;
  169. manager.querykey = responseObject[@"data"][@"querykey"];
  170. _secretkey = responseObject[@"data"];
  171. [manager openLock];
  172. }else{
  173. [CommonUtils hideHudForView:self.view];
  174. [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];
  175. [self reStartDevice];
  176. }
  177. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  178. NSLog(@"%@",error);
  179. [CommonUtils hideHudForView:self.view];
  180. [self reStartDevice];
  181. [CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];
  182. }];
  183. }
  184. - (void)centralManagerDidUpdateState:(CBCentralManager *)central{
  185. switch (central.state) {
  186. case CBCentralManagerStatePoweredOn:
  187. {
  188. _isBluetoothOpen = YES;
  189. [CommonUtils showTextHudModeWithInfo:@"蓝牙功能可用" view:self.view stayTime:1.5];
  190. }
  191. break;
  192. default:
  193. _isBluetoothOpen = NO;
  194. [CommonUtils showTextHudModeWithInfo:@"蓝牙处于关闭状态" view:self.view stayTime:1.5];
  195. break;
  196. }
  197. }

InputCodeViewController

  1. #import "InputCodeViewController.h"
  2. #import "ScanViewController.h"
  3. @interface InputCodeViewController ()
  4. @property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *labels
  5. @property (nonatomic) NSUInteger index;
  6. @property (nonatomic,strong) NSMutableArray *numArr;
  7. @end
  8. #define kBordColor [UIColor colorWithRed:208.f/255.f green:18.f/255.f blue:27.f/255.f alpha:1]
  9. @implementation InputCodeViewController
  10. - (void)viewDidLoad {
  11. [super viewDidLoad];
  12. self.navigationController.navigationBar.hidden = NO;
  13. _index = 0;
  14. _numArr = [NSMutableArray array];
  15. [self setUpNav];
  16. [self setUpLabel];
  17. }
  18. -(void)viewWillAppear:(BOOL)animated{
  19. [super viewWillAppear:animated];
  20. self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
  21. }
  22. -(void)viewWillDisappear:(BOOL)animated{
  23. [super viewWillDisappear:animated];
  24. self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor]};
  25. }
  26. - (void)setUpLabel{
  27. for (UILabel *label in _labels) {
  28. label.layer.borderColor = [UIColor whiteColor].CGColor;
  29. label.layer.borderWidth = 1;
  30. }
  31. UILabel *firstLabel = _labels[0];
  32. firstLabel.layer.borderColor = kBordColor.CGColor;
  33. firstLabel.layer.borderWidth = 1;
  34. }
  35. - (void)setUpNav{
  36. self.navigationController.navigationBar.hidden = NO;
  37. self.title = @"手动开锁";
  38. UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
  39. left.image = [UIImage imageNamed:@"back"];
  40. left.tintColor = [UIColor whiteColor];
  41. self.navigationItem.leftBarButtonItem = left;
  42. [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
  43. [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
  44. }
  45. - (void)close{
  46. [self.navigationController popViewControllerAnimated:YES];
  47. }
  48. - (IBAction)sure:(UIButton *)sender {
  49. if (_index<10) {
  50. return;
  51. }
  52. NSString *tem = [_numArr componentsJoinedByString:@","];
  53. NSString *codeStr = [tem stringByReplacingOccurrencesOfString:@"," withString:@""];
  54. NSArray *VCArr = self.navigationController.viewControllers;
  55. if (_isInputCode) {
  56. UIViewController *vc = VCArr[VCArr.count-3];
  57. [vc setValue:codeStr forKey:@"codeStr"];
  58. [self.navigationController popToViewController:vc animated:YES];
  59. }else{
  60. ScanViewController *vc = VCArr[VCArr.count-2];
  61. vc.codeStr = codeStr;
  62. [self.navigationController popViewControllerAnimated:YES];
  63. }
  64. }
  65. - (IBAction)clickNumPad:(UIButton *)sender {
  66. if (_index<10) {
  67. NSInteger num = sender.tag-100;
  68. UILabel *codeLabel = _labels[_index];
  69. codeLabel.layer.borderColor = [UIColor whiteColor].CGColor;
  70. codeLabel.layer.borderWidth = 1;
  71. codeLabel.text = [NSString stringWithFormat:@"%ld",(long)num];
  72. [_numArr addObject: sender.titleLabel.text];
  73. if (_index<9) {
  74. UILabel *label = _labels[_index+1];
  75. label.layer.borderColor = kBordColor.CGColor;
  76. label.layer.borderWidth = 1;
  77. }
  78. _index++;
  79. }
  80. }
  81. - (IBAction)deleteNum:(UIButton *)sender {
  82. if (_index == 0) {
  83. return;
  84. }
  85. [_numArr removeObject:sender.titleLabel.text];
  86. UILabel *codeLabel = _labels[_index-1];
  87. codeLabel.layer.borderColor = kBordColor.CGColor;
  88. codeLabel.layer.borderWidth = 1;
  89. codeLabel.text = @"";
  90. if (_index<10) {
  91. UILabel *label = _labels[_index];
  92. label.layer.borderColor = [UIColor whiteColor].CGColor;
  93. label.layer.borderWidth = 1;
  94. }
  95. _index--;
  96. }

WebViewController

  1. #import "WebViewController.h"
  2. #import <WebKit/WebKit.h>
  3. #import "Service1ViewController.h"
  4. #import "Service2ViewController.h"
  5. #import "Service3ViewController.h"
  6. #import "Service4ViewController.h"
  7. @interface WebViewController ()<WKUIDelegate,WKNavigationDelegate>
  8. @property (nonatomic,strong) WKWebView *webView;
  9. @property (nonatomic,strong) NSMutableDictionary *parameterDict;
  10. @end
  11. @implementation WebViewController
  12. - (void)viewDidLoad {
  13. [super viewDidLoad];
  14. // 配置webView
  15. [self setUpWebView];
  16. [self setUpNav];
  17. }
  18. -(void)viewWillAppear:(BOOL)animated{
  19. [super viewWillAppear:animated];
  20. }
  21. -(void)viewWillDisappear:(BOOL)animated{
  22. [super viewWillDisappear:animated]
  23. }
  24. - (void)setUpNav{
  25. self.navigationController.navigationBar.hidden = NO;
  26. self.title = @"用户指南";
  27. UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(close)];
  28. left.tintColor = [UIColor blackColor];
  29. self.navigationItem.leftBarButtonItem = left;
  30. //// self.navigationController.navigationBar.backgroundColor= [UIColor whiteColor];
  31. // [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
  32. }
  33. - (void)close{
  34. if (_webView.backForwardList.backList.count == 0) {
  35. [self.navigationController popViewControllerAnimated:YES];
  36. }else{
  37. [_webView goToBackForwardListItem:_webView.backForwardList.backItem];
  38. }
  39. }
  40. - (void)setUpWebView{
  41. self.edgesForExtendedLayout = UIRectEdgeNone;
  42. self.automaticallyAdjustsScrollViewInsets = NO;
  43. WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
  44. // 设置偏好设置
  45. config.preferences = [[WKPreferences alloc] init];
  46. // 默认为0
  47. config.preferences.minimumFontSize = 12;
  48. // 默认认为YES
  49. config.preferences.javaScriptEnabled = YES;
  50. // 在iOS上默认为NO,表示不能自动通过窗口打开
  51. config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
  52. config.allowsInlineMediaPlayback = YES;
  53. // web内容处理池
  54. config.processPool = [[WKProcessPool alloc] init];
  55. // 通过JS与webview内容交互
  56. config.userContentController = [[WKUserContentController alloc] init];
  57. // 注入JS对象名称AppModel,当JS通过AppModel来调用时,
  58. // 我们可以在WKScriptMessageHandler代理中接收到/Users/reew/Desktop/智橙生活/SHWiseHouse/Classes/Main/Controllers/ViewController.m
  59. // [config.userContentController addScriptMessageHandler:self name:@"AppModel"];
  60. //
  61. // [config.userContentController addScriptMessageHandler:self name:@"tianshan"];
  62. self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-64) configuration:config];
  63. self.webView.navigationDelegate = self;
  64. [self.view addSubview:self.webView];
  65. [(UIScrollView *)[[self.webView subviews] objectAtIndex:0] setBounces:NO];
  66. self.webView.allowsBackForwardNavigationGestures = NO;
  67. // 配置JavascriptBridgeBridge
  68. self.webView.UIDelegate = self;
  69. self.webView.scrollView.bounces = NO;
  70. // CGFloat phoneVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
  71. // if (phoneVersion >= 10.0) {
  72. // content = [content stringByReplacingOccurrencesOfString:@"<video" withString:@"<video playsinline"];
  73. // }else {
  74. // content = [content stringByReplacingOccurrencesOfString:@"<video" withString:@"<video webkit-playsinline"];
  75. // }
  76. NSURL *url = [NSURL URLWithString:_url];
  77. NSURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  78. [_webView loadRequest:request];
  79. }
  80. #pragma mark webview相关
  81. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
  82. NSLog(@"%@",navigationAction.request.URL);
  83. NSURL *url = navigationAction.request.URL;
  84. NSString *funStr = [[url.absoluteString componentsSeparatedByString:@"="] lastObject];
  85. if ([funStr isEqualToString:@"lock"]) {
  86. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];
  87. Service1ViewController *vc1 = [sb instantiateViewControllerWithIdentifier:@"service1"];
  88. [self.navigationController pushViewController:vc1 animated:YES];
  89. decisionHandler(WKNavigationActionPolicyCancel);
  90. }else if ([funStr isEqualToString:@"broken"]){
  91. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];
  92. Service2ViewController *vc2 = [sb instantiateViewControllerWithIdentifier:@"service2"];
  93. [self.navigationController pushViewController:vc2 animated:YES];
  94. decisionHandler(WKNavigationActionPolicyCancel);
  95. }else if ([funStr isEqualToString:@"reporet"]){
  96. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];
  97. Service3ViewController *vc3 = [sb instantiateViewControllerWithIdentifier:@"service3"];
  98. [self.navigationController pushViewController:vc3 animated:YES];
  99. decisionHandler(WKNavigationActionPolicyCancel);
  100. }else if ([funStr isEqualToString:@"others"]){
  101. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Home" bundle:[NSBundle mainBundle]];
  102. Service4ViewController *vc3 = [sb instantiateViewControllerWithIdentifier:@"service4"];
  103. [self.navigationController pushViewController:vc3 animated:YES];
  104. decisionHandler(WKNavigationActionPolicyCancel);
  105. }else{
  106. decisionHandler(WKNavigationActionPolicyAllow);
  107. }
  108. }

MessageTableViewController

  1. #import "MessageTableViewController.h"
  2. #import "Meesage.h"
  3. #import "MessageTableViewCell.h"
  4. #import <UIImageView+WebCache.h>
  5. @interface MessageTableViewController ()
  6. @property (nonatomic,strong) NSMutableArray <Meesage *>*messageArr
  7. @end
  8. @implementation MessageTableViewController
  9. - (void)viewDidLoad {
  10. [super viewDidLoad];
  11. [self setUpTableView];
  12. [self requestData];
  13. [self setNav];
  14. }
  15. - (void)setNav{
  16. self.navigationController.navigationBar.hidden = NO;
  17. self.title = @"消息";
  18. UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
  19. left.image = [UIImage imageNamed:@"back"];
  20. left.tintColor = [UIColor blackColor];
  21. self.navigationItem.leftBarButtonItem = left;
  22. self.navigationController.navigationBar.hidden = NO;
  23. }
  24. - (void)close{
  25. [self.navigationController popViewControllerAnimated:YES];
  26. }
  27. - (void)setUpTableView{
  28. self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
  29. [self.tableView registerNib:[UINib nibWithNibName:@"MessageTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"MessageTableViewCell"];
  30. self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  31. self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
  32. }
  33. - (void)requestData{
  34. [CommonUtils showLoadingHudWithView:self.view text:nil];
  35. NSString *url = [kBaseUrl stringByAppendingPathComponent:kGetNewsInfo];
  36. [CommonUtils sendNobodyPOST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  37. [CommonUtils hideHudForView:self.view];
  38. NSLog(@"%@",responseObject);
  39. NSString *status = responseObject[@"status"];
  40. NSString *msg = responseObject[@"msg"];
  41. if ([status integerValue] == 1) {
  42. _messageArr = [NSMutableArray array];
  43. for (NSDictionary *dict in responseObject[@"data"]) {
  44. Meesage *message = [[Meesage alloc] initMeesage:dict];
  45. [_messageArr addObject:message];
  46. }
  47. [self.tableView reloadData];
  48. }else{
  49. [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];
  50. }
  51. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
  52. NSLog(@"%@",error);
  53. [CommonUtils hideHudForView:self.view];
  54. [CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];
  55. }];
  56. }
  57. - (NSString *)getTimeStrWithTimetap:(NSString *)timetamp{
  58. NSDateFormatter *stampFormatter = [[NSDateFormatter alloc] init];
  59. [stampFormatter setDateFormat:@"YYYY-MM-dd"];
  60. //以 1970/01/01 GMT为基准,然后过了secs秒的时间
  61. NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timetamp integerValue]/1000];
  62. NSString *timeStr = [stampFormatter stringFromDate:date];
  63. return timeStr;
  64. }
  65. #pragma mark - Table view data source
  66. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  67. return 1;
  68. }
  69. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  70. return _messageArr.count;
  71. }
  72. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  73. return kScreenW*64/145+70;
  74. }
  75. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  76. MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MessageTableViewCell" forIndexPath:indexPath];
  77. cell.selectionStyle = UITableViewCellSelectionStyleNone;
  78. Meesage *news = _messageArr[indexPath.row];
  79. [cell.image sd_setImageWithURL:[NSURL URLWithString:news.imgUrl] placeholderImage:nil];
  80. cell.newsTitle.text = news.newsTitle;
  81. cell.startTime.text = [self getTimeStrWithTimetap:news.starttime];
  82. NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
  83. NSTimeInterval time=[date timeIntervalSince1970]*1000;
  84. if (time > [news.endtime floatValue]) {
  85. cell.usable.hidden = NO;
  86. }else{
  87. cell.usable.hidden = YES;
  88. }
  89. return cell;
  90. }

LoginViewController

  1. #import "LoginViewController.h"
  2. #import "CommonUtils.h"
  3. #import <MBProgressHUD.h>
  4. #import "CommonUtils.h"
  5. #import <AFNetworking.h>
  6. #import "Login.h"
  7. #import "Account.h"
  8. #import "AuthViewController.h"
  9. #import "WebViewController.h"
  10. @interface LoginViewController ()<UITextFieldDelegate>
  11. @property (weak, nonatomic) IBOutlet UITextField *phone;
  12. @property (weak, nonatomic) IBOutlet UITextField *authCode;
  13. @property (weak, nonatomic) IBOutlet UIButton *getAuthCodeBtn;
  14. @property (weak, nonatomic) IBOutlet UIButton *sureBtn;
  15. @property (weak, nonatomic) IBOutlet UIButton *wxLogin;
  16. @end
  17. NSTimer *timer;
  18. static int timeValue = 60;
  19. @implementation LoginViewController
  20. - (void)viewDidLoad {
  21. [super viewDidLoad];
  22. _phone.delegate = self;
  23. _authCode.delegate = self;
  24. // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFielddidChangeValue) name:UITextFieldTextDidChangeNotification object:nil];
  25. _wxLogin.layer.cornerRadius = 20;
  26. _wxLogin.clipsToBounds = YES;
  27. _wxLogin.layer.borderColor = [UIColor colorWithRed:116.f/255.f green:197.f/255.f blue:68.f/255.f alpha:1].CGColor;
  28. _wxLogin.layer.borderWidth = 0.5;
  29. _getAuthCodeBtn.layer.cornerRadius = 15;
  30. _getAuthCodeBtn.clipsToBounds = YES;
  31. _sureBtn.layer.cornerRadius = 20;
  32. _sureBtn.clipsToBounds = YES;
  33. }
  34. -(void)viewWillAppear:(BOOL)animated{
  35. [super viewWillAppear:animated];
  36. self.navigationController.navigationBar.hidden = NO;
  37. [self setUpNav];
  38. }
  39. - (void)setUpNav{
  40. self.navigationController.navigationBar.hidden = NO;
  41. self.title = @"手机验证";
  42. UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(closePage)];
  43. left.image = [UIImage imageNamed:@"back"];
  44. left.tintColor = [UIColor blackColor];
  45. self.navigationItem.leftBarButtonItem = left;
  46. [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
  47. [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
  48. }
  49. - (void)closePage{
  50. [self.navigationController popViewControllerAnimated:YES];
  51. }
  52. - (void)wxErr{
  53. [CommonUtils showTextHudModeWithInfo:@"支付失败" view:self.view stayTime:1.5];
  54. }
  55. - (IBAction)close:(UIButton *)sender {
  56. [self skipHome];
  57. }
  58. - (IBAction)WXKLogin:(UIButton *)sender {
  59. }
  60. - (IBAction)SkipAgreement:(UIButton *)sender {
  61. WebViewController *vc = [[WebViewController alloc] init];
  62. vc.url = @"http://manage.mabaoxc.com/p/notify/getNotify?id=1";
  63. [self.navigationController pushViewController:vc animated:YES];
  64. }
  65. - (void)skipHome{
  66. [self.navigationController popToRootViewControllerAnimated:YES];
  67. }
  68. - (void)dealYzmBut{
  69. if (timeValue == 0) {
  70. // [_rightView setBackgroundColor:[UIColor colorWithRed:53/255.0 green:163/255.0 blue:223/255.0 alpha:1]];
  71. // _getAuthCodeBtn.backgroundColor = [UIColor colorWithRed:51.f/255.f green:51.f/255.f blue:51.f/255.f alpha:1];
  72. [_getAuthCodeBtn setTitle:@"获取验证码" forState:0];
  73. _getAuthCodeBtn.userInteractionEnabled = YES;
  74. timeValue = 60;
  75. [timer invalidate];
  76. return;
  77. }
  78. [_getAuthCodeBtn setTitle:[NSString stringWithFormat:@"%ds",timeValue] forState:0];
  79. // _getAuthCodeBtn.backgroundColor = [UIColor grayColor];
  80. _getAuthCodeBtn.userInteractionEnabled = NO;
  81. timeValue--;
  82. }
  83. - (IBAction)getAuthCode:(UIButton *)sender {
  84. if (![CommonUtils isPhoneNum:_phone.text]) {
  85. [CommonUtils showTextHudModeWithInfo:@"请输入正确的手机号" view:self.view stayTime:1.5];
  86. }else{
  87. // timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(dealYzmBut) userInfo:nil repeats:YES];
  88. [_phone resignFirstResponder];
  89. NSString *IMEI = [CommonUtils getDeviceUUID];
  90. NSString *sign = [CommonUtils getSign];
  91. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  92. [manager.requestSerializer setValue:sign forHTTPHeaderField:@"SIGN"];
  93. NSString *url = [kBaseUrl stringByAppendingPathComponent:kSendsms];
  94. [CommonUtils showLoadingHudModelWithView:self.view handle:^{
  95. }];
  96. [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  97. [formData appendPartWithFormData:[_phone.text dataUsingEncoding:NSUTF8StringEncoding] name:@"mobile"];
  98. [formData appendPartWithFormData:[IMEI dataUsingEncoding:NSUTF8StringEncoding] name:@"IMEI"];
  99. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  100. NSLog(@"%@",responseObject);
  101. NSString *msg = responseObject[@"msg"];
  102. NSString *status = responseObject[@"status"];
  103. if ([status integerValue] == 1) {
  104. timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(dealYzmBut) userInfo:nil repeats:YES];
  105. }
  106. [CommonUtils hideHudForView:self.view];
  107. [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];
  108. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  109. NSLog(@"%@",error);
  110. [CommonUtils hideHudForView:self.view];
  111. [CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];
  112. }];
  113. }
  114. }
  115. - (IBAction)login:(UIButton *)sender {
  116. // UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Login" bundle:[NSBundle mainBundle]];
  117. // AuthViewController *authVC = [sb instantiateViewControllerWithIdentifier:@"auth"];
  118. // [self presentViewController:authVC animated:YES completion:nil];
  119. //输入信息判断提示
  120. if (![CommonUtils isPhoneNum:_phone.text]) {
  121. [CommonUtils showTextHudModeWithInfo:@"请输入正确的手机号码" view:self.view stayTime:1];
  122. }else if (_authCode.text.length==0){
  123. [CommonUtils showTextHudModeWithInfo:@"请输入验证码" view:self.view stayTime:1];
  124. }else{
  125. //请求登录
  126. [CommonUtils showLoadingHudModelWithView:self.view handle:nil];
  127. NSString *url = [kBaseUrl stringByAppendingPathComponent:kLogin];
  128. NSString *SIGN = [CommonUtils getSign];
  129. NSString *IMEI = [CommonUtils getDeviceUUID];
  130. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  131. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  132. [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  133. //参数
  134. [formData appendPartWithFormData:[_phone.text dataUsingEncoding:NSUTF8StringEncoding] name:@"mobile"];
  135. [formData appendPartWithFormData:[_authCode.text dataUsingEncoding:NSUTF8StringEncoding] name:@"code"];
  136. [formData appendPartWithFormData:[IMEI dataUsingEncoding:NSUTF8StringEncoding] name:@"IMEI"];
  137. [formData appendPartWithFormData:[@"2" dataUsingEncoding:NSUTF8StringEncoding] name:@"client"];
  138. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  139. [CommonUtils hideHudForView:self.view];
  140. NSLog(@"%@",responseObject);
  141. NSString *status = responseObject[@"status"];
  142. NSString *msg = responseObject[@"msg"];
  143. if ([status integerValue] == 1) {
  144. //登录成功,保存用户数据,跳转实名认证;
  145. [[Account shareAccount] saveUserInfo:responseObject[@"data"]];
  146. [[NSUserDefaults standardUserDefaults] setObject:responseObject[@"data"][@"auth"] forKey:@"auth"];
  147. if ([responseObject[@"data"][@"verified"] isEqualToString:@"0"]) {
  148. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Login" bundle:[NSBundle mainBundle]];
  149. AuthViewController *authVC = [sb instantiateViewControllerWithIdentifier:@"auth"];
  150. [self.navigationController pushViewController:authVC animated:YES];
  151. }else{
  152. [self.navigationController popToRootViewControllerAnimated:YES];
  153. }
  154. }else{
  155. [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];
  156. }
  157. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  158. NSLog(@"%@",error);
  159. [CommonUtils hideHudForView:self.view];
  160. [CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];
  161. }];
  162. }
  163. }
  164. - (void)didReceiveMemoryWarning {
  165. [super didReceiveMemoryWarning];
  166. // Dispose of any resources that can be recreated.
  167. }
  168. - (IBAction)skipProvision:(UIButton *)sender {
  169. }
  170. -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
  171. [_phone resignFirstResponder];
  172. [_authCode resignFirstResponder];
  173. }

DepositViewController

  1. #import "DepositViewController.h"
  2. #import "PayTypeViewController.h"
  3. #import "Home.h"
  4. #import "CommonUtils.h"
  5. #import "Account.h"
  6. #import "Pay.h"
  7. #import "Account.h"
  8. #import <AlipaySDK/AlipaySDK.h>
  9. #import "UserInfo.h"
  10. #import "WXApi.h"
  11. #import "WXApiObject.h"
  12. @interface DepositViewController ()
  13. @property (weak, nonatomic) IBOutlet UIButton *continueBtn;
  14. @property (weak, nonatomic) IBOutlet UIView *otherView;
  15. @property (weak, nonatomic) IBOutlet UIImageView *bgImg;
  16. @property (nonatomic,strong) UIView *coverView;
  17. @property (weak, nonatomic) IBOutlet UILabel *despositLabel;
  18. @property (nonatomic,strong) NSString *desposit;
  19. @property (weak, nonatomic) IBOutlet UIView *AlView;
  20. @property (weak, nonatomic) IBOutlet UIView *WXView;
  21. @property (weak, nonatomic) IBOutlet UIImageView *ALSelect;
  22. @property (weak, nonatomic) IBOutlet UIImageView *WXSelect;
  23. @property (nonatomic) BOOL isALPay;
  24. @end
  25. @implementation DepositViewController
  26. - (void)viewDidLoad {
  27. [super viewDidLoad];
  28. [self setOtherView];
  29. [self requestDeposit];
  30. [self setUpNav];
  31. [self setUpPayView];
  32. [self drawColor];
  33. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closePage) name:@"finishWXPay" object:nil];
  34. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxErr) name:@"wxpayerr" object:nil];
  35. }
  36. -(void)viewWillAppear:(BOOL)animated{
  37. [super viewWillAppear:animated];
  38. self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
  39. }
  40. -(void)viewWillDisappear:(BOOL)animated{
  41. [super viewWillDisappear:animated];
  42. self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor]};
  43. [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:0];
  44. [self.navigationController.navigationBar setShadowImage:nil];
  45. }
  46. - (void)wxErr{
  47. [CommonUtils showTextHudModeWithInfo:@"支付失败" view:self.view stayTime:1.5];
  48. }
  49. - (void)setUpPayView{
  50. UITapGestureRecognizer *tapGestureRecognizer2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectALPay)];
  51. [_AlView addGestureRecognizer:tapGestureRecognizer2];
  52. _isALPay = YES;
  53. UITapGestureRecognizer *tapGestureRecognizer3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectWXPay)];
  54. [_WXView addGestureRecognizer:tapGestureRecognizer3];
  55. }
  56. - (void)selectALPay{
  57. _ALSelect.image = [UIImage imageNamed:@"withdraw_success"];
  58. _WXSelect.image = [UIImage imageNamed:@"Unchecked"];
  59. _isALPay = YES;
  60. }
  61. - (void)selectWXPay{
  62. _ALSelect.image = [UIImage imageNamed:@"Unchecked"];
  63. _WXSelect.image = [UIImage imageNamed:@"withdraw_success"];
  64. _isALPay = NO;
  65. }
  66. - (void)setUpNav{
  67. self.navigationController.navigationBar.hidden = NO;
  68. self.title = @"缴纳押金";
  69. UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
  70. left.image = [UIImage imageNamed:@"back"];
  71. left.tintColor = [UIColor whiteColor];
  72. self.navigationItem.leftBarButtonItem = left;
  73. [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
  74. [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
  75. }
  76. - (void)close{
  77. if (_isFromLogin) {
  78. [self closePage];
  79. }else{
  80. [self.navigationController popViewControllerAnimated:YES];
  81. }
  82. }
  83. - (void)setOtherView{
  84. self.navigationController.navigationBar.hidden = YES;
  85. _continueBtn.layer.cornerRadius = _continueBtn.bounds.size.height/2;
  86. _continueBtn.clipsToBounds = YES;;
  87. _coverView = [[UIView alloc] initWithFrame:self.view.bounds];
  88. [self.view addSubview:_coverView];
  89. _coverView.backgroundColor = [UIColor whiteColor];
  90. [self.view bringSubviewToFront:_coverView];
  91. }
  92. - (void)drawColor{
  93. CAGradientLayer *gradientLayer = [CAGradientLayer layer];
  94. UIColor *beginColor = [UIColor colorWithRed:210.f/255.f green:20/255.f blue:25.f/255.f alpha:1];
  95. UIColor *endColor = [UIColor colorWithRed:240.f/255.f green:130.f/255.f blue:45.f/255.f alpha:1];
  96. gradientLayer.colors = @[(__bridge id)beginColor.CGColor, (__bridge id)endColor.CGColor];
  97. gradientLayer.locations = @[@0.1,@1.0];
  98. gradientLayer.startPoint = CGPointMake(0, 0);
  99. gradientLayer.endPoint = CGPointMake(1.0, 0);
  100. gradientLayer.frame = CGRectMake(0, 0, kScreenW, _continueBtn.bounds.size.height);
  101. [self.continueBtn.layer addSublayer:gradientLayer];
  102. }
  103. - (void)requestDeposit{
  104. [CommonUtils showLoadingHudModelWithView:self.view handle:nil];
  105. NSString *url = [kBaseUrl stringByAppendingPathComponent:kGetDeposit];
  106. NSString *SIGN = [CommonUtils getSign];
  107. NSString *AUTH = [Account shareAccount].user.auth;
  108. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  109. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  110. [manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];
  111. [manager POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  112. [CommonUtils hideHudForView:self.view];
  113. NSLog(@"%@",responseObject);
  114. NSString *status = responseObject[@"status"];
  115. NSString *msg = responseObject[@"msg"];
  116. if ([status integerValue] == 1) {
  117. _coverView.hidden = YES;
  118. _despositLabel.text = [NSString stringWithFormat:@"%.2f",[responseObject[@"data"] floatValue]/100];
  119. _desposit = [NSString stringWithFormat:@"%.2f元",[responseObject[@"data"] floatValue]/100];
  120. }else{
  121. [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];
  122. }
  123. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {\
  124. NSLog(@"%@",error);
  125. [CommonUtils hideHudForView:self.view];
  126. [CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];
  127. }];
  128. }
  129. - (void)closePage{
  130. [self.navigationController popToRootViewControllerAnimated:YES];
  131. }
  132. - (IBAction)next:(UIButton *)sender {
  133. // UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Login" bundle:[NSBundle mainBundle]];
  134. // PayTypeViewController *vc = [sb instantiateViewControllerWithIdentifier:@"payType"];
  135. // vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
  136. // vc.isFromLogin = _isFromLogin;
  137. // vc.price = _desposit;
  138. // [self presentViewController:vc animated:YES completion:nil];
  139. [self payDeposit];
  140. }
  141. #pragma mark - 支付
  142. - (void)payDeposit{
  143. [CommonUtils showLoadingHudModelWithView:self.view handle:nil];
  144. NSString *url = [kBaseUrl stringByAppendingPathComponent:kPaydeposit];
  145. NSString *SIGN = [CommonUtils getSign];
  146. NSString *AUTH = [Account shareAccount].user.auth;
  147. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  148. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  149. [manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];
  150. [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  151. //参数
  152. NSString *payment;
  153. if (_isALPay) {
  154. payment = @"1";
  155. }else{
  156. payment = @"2";
  157. }
  158. [formData appendPartWithFormData:[payment dataUsingEncoding:NSUTF8StringEncoding] name:@"payment"];
  159. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  160. NSLog(@"%@",responseObject);
  161. [CommonUtils hideHudForView:self.view];
  162. NSString *status = responseObject[@"status"];
  163. NSString *msg = responseObject[@"msg"];
  164. if ([status integerValue] == 1) {
  165. //验证成功
  166. if (_isALPay) {
  167. [self AliPay:responseObject];
  168. }else{
  169. [self WXPay:responseObject[@"data"]];
  170. }
  171. }else{
  172. [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];
  173. }
  174. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  175. NSLog(@"%@",error);
  176. [CommonUtils hideHudForView:self.view];
  177. [CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];
  178. }];
  179. }
  180. - (void)AliPay:(NSDictionary *)responseObject{
  181. //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
  182. NSString *appScheme = @"mengbei";
  183. // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
  184. NSString *orderString = responseObject[@"data"];
  185. // NOTE: 调用支付结果开始支付
  186. [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
  187. NSLog(@"reslut = %@",resultDic);
  188. NSString *statusCode = resultDic[@"resultStatus"];
  189. if ([statusCode isEqual:@"9000"]) {//
  190. //关闭页面
  191. [CommonUtils showTextHudModeWithInfo:@"支付成功" view:self.view stayTime:1.5];
  192. [self closePage];
  193. //修改用户信息
  194. [Account shareAccount].user.hasdeposit = @"1";
  195. [[Account shareAccount] saveInfo];
  196. }else{
  197. [CommonUtils showTextHudModeWithInfo:@"支付失败" view:self.view stayTime:1.5];
  198. }
  199. }];
  200. }
  201. - (void)WXPay:(NSDictionary *)responseObject{
  202. PayReq *request = [[PayReq alloc] init] ;
  203. request.partnerId = responseObject[@"partnerid"];
  204. request.prepayId= responseObject[@"prepayid"];
  205. request.package = @"Sign=WXPay";
  206. request.nonceStr= responseObject[@"noncestr"];
  207. request.timeStamp= [responseObject[@"timestamp"] intValue];
  208. request.sign= responseObject[@"sign"];
  209. BOOL success = [WXApi sendReq:request];
  210. }
  211. - (void)didReceiveMemoryWarning {
  212. [super didReceiveMemoryWarning];
  213. // Dispose of any resources that can be recreated.
  214. }

PayTypeViewController

  1. #import "PayTypeViewController.h"
  2. #import "CommonUtils.h"
  3. #import "Pay.h"
  4. #import "Account.h"
  5. #import <AlipaySDK/AlipaySDK.h>
  6. #import "UserInfo.h"
  7. #import "WXApi.h"
  8. #import "WXApiObject.h"
  9. #import <MapKit/MapKit.h>
  10. #import <AMapFoundationKit/AMapFoundationKit.h>
  11. //#import <AMapLocationKit/>
  12. @interface PayTypeViewController ()<UIGestureRecognizerDelegate>
  13. @property (weak, nonatomic) IBOutlet UIView *AlView;
  14. @property (weak, nonatomic) IBOutlet UIView *WXView;
  15. @property (weak, nonatomic) IBOutlet UIImageView *ALSelect;
  16. @property (weak, nonatomic) IBOutlet UIImageView *WXSelect;
  17. @property (weak, nonatomic) IBOutlet UIButton *payBtn;
  18. @property (weak, nonatomic) IBOutlet UIView *temView;
  19. @property (weak, nonatomic) IBOutlet UIView *bgView;
  20. @property (nonatomic) BOOL isALPay;
  21. @property (weak, nonatomic) IBOutlet UILabel *payTypeTitle;
  22. @property (weak, nonatomic) IBOutlet UILabel *payCount;
  23. @end
  24. @implementation PayTypeViewController
  25. - (void)viewDidLoad {
  26. [super viewDidLoad];
  27. _isALPay = YES;
  28. self.view.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.6];
  29. UITapGestureRecognizer *tapGestureRecognizer1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismisVC)];
  30. [self.view addGestureRecognizer:tapGestureRecognizer1];
  31. tapGestureRecognizer1.delegate = self;
  32. UITapGestureRecognizer *tapGestureRecognizer2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectALPay)];
  33. [_AlView addGestureRecognizer:tapGestureRecognizer2];
  34. UITapGestureRecognizer *tapGestureRecognizer3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectWXPay)];
  35. [_WXView addGestureRecognizer:tapGestureRecognizer3];
  36. //wxpayerr
  37. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(closePage) name:@"finishWXPay" object:nil];
  38. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxErr) name:@"wxpayerr" object:nil];
  39. _payCount.text = _price;
  40. if (_isFromMall) {
  41. _payTypeTitle.text = @"需支付";
  42. }else{
  43. _payTypeTitle.text = @"缴纳押金(可退)";
  44. }
  45. }
  46. //- (void)setUserLocalion{
  47. // MAUserLocationRepresentation *r = [[MAUserLocationRepresentation alloc] init];
  48. // r.showsAccuracyRing = NO;///精度圈是否显示,默认YES
  49. //}
  50. - (void)wxErr{
  51. [CommonUtils showTextHudModeWithInfo:@"支付失败" view:self.view stayTime:1.5];
  52. }
  53. -(void)dismisVC{
  54. [self dismissViewControllerAnimated:YES completion:nil];
  55. }
  56. - (void)selectALPay{
  57. _ALSelect.image = [UIImage imageNamed:@"withdraw_success"];
  58. _WXSelect.image = [UIImage imageNamed:@"Unchecked"];
  59. _isALPay = YES;
  60. }
  61. - (void)selectWXPay{
  62. _ALSelect.image = [UIImage imageNamed:@"Unchecked"];
  63. _WXSelect.image = [UIImage imageNamed:@"withdraw_success"];
  64. _isALPay = NO;
  65. }
  66. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
  67. {
  68. if ( [touch.view isDescendantOfView:_bgView]) {
  69. return NO;
  70. }
  71. return YES;
  72. }
  73. - (void)payDeposit{
  74. [CommonUtils showLoadingHudModelWithView:self.view handle:nil];
  75. NSString *url = [kBaseUrl stringByAppendingPathComponent:kPaydeposit];
  76. NSString *SIGN = [CommonUtils getSign];
  77. NSString *AUTH = [Account shareAccount].user.auth;
  78. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  79. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  80. [manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];
  81. [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  82. //参数
  83. NSString *payment;
  84. if (_isALPay) {
  85. payment = @"1";
  86. }else{
  87. payment = @"2";
  88. }
  89. [formData appendPartWithFormData:[payment dataUsingEncoding:NSUTF8StringEncoding] name:@"payment"];
  90. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  91. NSLog(@"%@",responseObject);
  92. [CommonUtils hideHudForView:self.view];
  93. NSString *status = responseObject[@"status"];
  94. NSString *msg = responseObject[@"msg"];
  95. if ([status integerValue] == 1) {
  96. //验证成功
  97. if (_isALPay) {
  98. [self AliPay:responseObject];
  99. }else{
  100. [self WXPay:responseObject[@"data"]];
  101. }
  102. }else{
  103. [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];
  104. }
  105. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  106. NSLog(@"%@",error);
  107. [CommonUtils hideHudForView:self.view];
  108. [CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];
  109. }];
  110. }
  111. - (void)payMallGoods{
  112. [CommonUtils showLoadingHudModelWithView:self.view handle:nil];
  113. NSString *url = [kBaseUrl stringByAppendingPathComponent:kAddGoodsOrder];
  114. [CommonUtils sendPOST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  115. [formData appendPartWithFormData:[_goodsNo dataUsingEncoding:NSUTF8StringEncoding] name:@"goodsNo"];
  116. [formData appendPartWithFormData:[_phone dataUsingEncoding:NSUTF8StringEncoding] name:@"phone"];
  117. [formData appendPartWithFormData:[_address dataUsingEncoding:NSUTF8StringEncoding] name:@"address"];
  118. [formData appendPartWithFormData:[_name dataUsingEncoding:NSUTF8StringEncoding] name:@"name"];
  119. [formData appendPartWithFormData:[_postal dataUsingEncoding:NSUTF8StringEncoding] name:@"postal"];
  120. if (_isALPay) {
  121. [formData appendPartWithFormData:[@"1" dataUsingEncoding:NSUTF8StringEncoding] name:@"pay"];
  122. }else{
  123. [formData appendPartWithFormData:[@"0" dataUsingEncoding:NSUTF8StringEncoding] name:@"pay"];
  124. }
  125. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  126. NSLog(@"%@",responseObject);
  127. [CommonUtils hideHudForView:self.view];
  128. NSString *status = responseObject[@"status"];
  129. NSString *msg = responseObject[@"msg"];
  130. if ([status integerValue] == 1) {
  131. //验证成功
  132. if (_isALPay) {
  133. [self AliPay:responseObject];
  134. }else{
  135. [self WXPay:responseObject[@"data"]];
  136. }
  137. }else{
  138. [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];
  139. }
  140. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
  141. NSLog(@"%@",error);
  142. [CommonUtils hideHudForView:self.view];
  143. [CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];
  144. }];
  145. }
  146. - (IBAction)pay:(UIButton *)sender {
  147. if (_isFromMall) {
  148. [self payMallGoods];
  149. }else{
  150. [self payDeposit];
  151. }
  152. }
  153. - (void)closePage{
  154. //修改用户信息
  155. [Account shareAccount].user.hasdeposit = @"1";
  156. [[Account shareAccount] saveInfo];
  157. [self dismissViewControllerAnimated:YES completion:^{
  158. }];
  159. UINavigationController *nav = (UINavigationController *)self.presentingViewController;
  160. [nav popToRootViewControllerAnimated:YES];
  161. }
  162. - (void)AliPay:(NSDictionary *)responseObject{
  163. //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
  164. NSString *appScheme = @"mengbei";
  165. // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
  166. NSString *orderString = responseObject[@"data"];
  167. // NOTE: 调用支付结果开始支付
  168. [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
  169. NSLog(@"reslut = %@",resultDic);
  170. NSString *statusCode = resultDic[@"resultStatus"];
  171. if ([statusCode isEqual:@"9000"]) {//
  172. //关闭页面
  173. [CommonUtils showTextHudModeWithInfo:@"支付成功" view:self.view stayTime:1.5];
  174. [self closePage];
  175. //修改用户信息
  176. [Account shareAccount].user.hasdeposit = @"1";
  177. [[Account shareAccount] saveInfo];
  178. }else{
  179. [CommonUtils showTextHudModeWithInfo:@"支付失败" view:self.view stayTime:1.5];
  180. }
  181. }]
  182. }
  183. - (void)WXPay:(NSDictionary *)responseObject{
  184. PayReq *request = [[PayReq alloc] init] ;
  185. request.partnerId = responseObject[@"partnerid"];
  186. request.prepayId= responseObject[@"prepayid"];
  187. request.package = @"Sign=WXPay";
  188. request.nonceStr= responseObject[@"noncestr"];
  189. request.timeStamp= [responseObject[@"timestamp"] intValue];
  190. request.sign= responseObject[@"sign"];
  191. BOOL success = [WXApi sendReq:request];
  192. }

CommonUtils

  1. #import "CommonUtils.h"
  2. #import <MBProgressHUD.h>
  3. #import <SAMKeychain.h>
  4. #import "CommonCrypto/CommonDigest.h"
  5. #import "sys/utsname.h"
  6. @implementation CommonUtils
  7. +(BOOL)isIDCard:(NSString *)identityString{
  8. if (identityString.length != 18) return NO;
  9. // 正则表达式判断基本 身份证号是否满足格式
  10. 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)$";
  11. // 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])$)$";
  12. NSPredicate *identityStringPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
  13. //如果通过该验证,说明身份证格式正确,但准确性还需计算
  14. if(![identityStringPredicate evaluateWithObject:identityString]) return NO;
  15. //** 开始进行校验 *//
  16. //将前17位加权因子保存在数组里
  17. NSArray *idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
  18. //这是除以11后,可能产生的11位余数、验证码,也保存成数组
  19. NSArray *idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
  20. //用来保存前17位各自乖以加权因子后的总和
  21. NSInteger idCardWiSum = 0;
  22. for(int i = 0;i < 17;i++) {
  23. NSInteger subStrIndex = [[identityString substringWithRange:NSMakeRange(i, 1)] integerValue];
  24. NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
  25. idCardWiSum+= subStrIndex * idCardWiIndex;
  26. }
  27. //计算出校验码所在数组的位置
  28. NSInteger idCardMod=idCardWiSum%11;
  29. //得到最后一位身份证号码
  30. NSString *idCardLast= [identityString substringWithRange:NSMakeRange(17, 1)];
  31. //如果等于2,则说明校验码是10,身份证号码最后一位应该是X
  32. if(idCardMod==2) {
  33. if(![idCardLast isEqualToString:@"X"]|| ![idCardLast isEqualToString:@"x"]) {
  34. return NO;
  35. }
  36. }
  37. else{
  38. //用计算出的验证码与最后一位身份证号码匹配,如果一致,说明通过,否则是无效的身份证号码
  39. if(![idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]]) {
  40. return NO;
  41. }
  42. }
  43. return YES;
  44. }
  45. +(BOOL)isPhoneNum:(NSString *)phone{
  46. NSString *predicate = @"^[1][3,4,5,6,7,8][0-9]{9}$";
  47. // @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[06-8])\\d{8}$";
  48. NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", predicate];
  49. return [regextestmobile evaluateWithObject:phone];
  50. }
  51. +(void)showTextHudModeWithInfo:(NSString *)infoStr view:(UIView *)view stayTime:(float)time{
  52. MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
  53. hud.mode = MBProgressHUDModeText;
  54. hud.label.text = infoStr;
  55. hud.offset = CGPointMake(1.f, 230);
  56. hud.contentColor = [UIColor whiteColor];
  57. hud.bezelView.color= [UIColor blackColor];
  58. hud.label.font = [UIFont systemFontOfSize:14];
  59. hud.minSize = CGSizeMake(100, 30);
  60. [hud hideAnimated:YES afterDelay:time];
  61. }
  62. + (void)showLoadingHudModelWithView:(UIView *)view handle:(void (^)(void))dosome{
  63. MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
  64. hud.mode = MBProgressHUDModeIndeterminate;
  65. }
  66. + (void)showLoadingHudWithView:(UIView *)view text:(NSString *)text{
  67. MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
  68. hud.mode = MBProgressHUDModeIndeterminate;
  69. hud.detailsLabel.text = text;
  70. }
  71. +(void)hideHudForView:(UIView *)view{
  72. [MBProgressHUD hideHUDForView:view animated:YES];
  73. }
  74. +(AFHTTPSessionManager *)getAFHTTPSessionManager{
  75. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  76. manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  77. manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/javascript", @"text/html",@"image/png",nil];
  78. manager.requestSerializer = [AFHTTPRequestSerializer serializer];
  79. manager.responseSerializer =[AFJSONResponseSerializer serializer];//以json格式返回
  80. manager.requestSerializer = [AFJSONRequestSerializer serializer];//以json格式提交
  81. manager.requestSerializer.timeoutInterval = 10.0f;
  82. return manager;
  83. }
  84. +(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{
  85. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  86. manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  87. manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/javascript", @"text/html",@"image/png",nil];
  88. manager.requestSerializer = [AFHTTPRequestSerializer serializer];
  89. manager.responseSerializer =[AFJSONResponseSerializer serializer];//以json格式返回
  90. manager.requestSerializer = [AFJSONRequestSerializer serializer];//以json格式提交
  91. manager.requestSerializer.timeoutInterval = 10.0f;
  92. NSString *SIGN = [CommonUtils getSign];
  93. NSString *AUTH = [Account shareAccount].user.auth;
  94. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  95. [manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];
  96. [manager POST:URLString parameters:parameters constructingBodyWithBlock:block progress:uploadProgress success:success failure:failure];
  97. }
  98. +(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{
  99. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  100. manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  101. manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/javascript", @"text/html",@"image/png",nil];
  102. manager.requestSerializer = [AFHTTPRequestSerializer serializer];
  103. manager.responseSerializer =[AFJSONResponseSerializer serializer];//以json格式返回
  104. manager.requestSerializer = [AFJSONRequestSerializer serializer];//以json格式提交
  105. manager.requestSerializer.timeoutInterval = 10.0f;
  106. NSString *SIGN = [CommonUtils getSign];
  107. NSString *AUTH = [Account shareAccount].user.auth;
  108. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  109. [manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];
  110. [manager POST:URLString parameters:parameters progress:uploadProgress success:success failure:failure];
  111. }
  112. +(NSString *)getDeviceUUID{
  113. NSString *uuid = [SAMKeychain passwordForService:@"" account:@"uuid"];
  114. if (uuid == nil || [uuid isEqual:@""]) {
  115. NSUUID *curentuuid = [[UIDevice currentDevice] identifierForVendor];
  116. uuid = [curentuuid UUIDString];
  117. uuid = [uuid stringByReplacingOccurrencesOfString:@"-" withString:@""];
  118. [SAMKeychain setPassword:uuid forService:@"" account:@"uuid"];
  119. }
  120. return uuid;
  121. }
  122. +(NSString *)getNowTimestamp{
  123. NSDate *nowDate = [NSDate dateWithTimeIntervalSinceNow:0];
  124. NSTimeInterval time = [nowDate timeIntervalSince1970] *1000;
  125. NSString *timestamp = [NSString stringWithFormat:@"%.0f",time];
  126. return timestamp;
  127. }
  128. +(NSString *)getMD5StrWithString:(NSString *)str{
  129. const char *cStr = [str UTF8String];
  130. unsigned char digest[CC_MD5_DIGEST_LENGTH];
  131. CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
  132. NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
  133. for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
  134. [result appendFormat:@"%02x", digest[i]];
  135. }
  136. return result;
  137. }
  138. +(NSString *)getSign{
  139. //时间戳
  140. NSString *timestamp = [self getNowTimestamp];
  141. NSString *key = @"Mombo@Zhou";
  142. NSString *temStr = [NSString stringWithFormat:@"%@.%@",key,timestamp];
  143. NSString *md5Str = [self getMD5StrWithString:temStr];
  144. NSString *sign = [NSString stringWithFormat:@"%@.%@",timestamp,md5Str];
  145. return sign;
  146. }
  147. +(float)getDifSinceNowWithTimetamp:(NSString *)timetamp{
  148. NSDate* nowdate = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
  149. NSTimeInterval time=[nowdate timeIntervalSince1970]*1000;// *1000 是精确到毫秒,不乘就是精确到秒
  150. float tem = (time-[timetamp floatValue]);
  151. if (tem < 0) {
  152. return 0;
  153. }else{
  154. return tem;
  155. }
  156. }
  157. + (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{
  158. UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
  159. UIAlertAction *act1 = [UIAlertAction actionWithTitle:title1 style:style1 handler:handler1];
  160. UIAlertAction *act2 = [UIAlertAction actionWithTitle:title2 style:style2 handler:handler2];
  161. [alert addAction:act1];
  162. [alert addAction:act2];
  163. [VC presentViewController:alert animated:YES completion:nil];
  164. }
  165. + (CGFloat)getStringHeightWithFontSize:(CGFloat)font string:(NSString *)str andWidth:(CGFloat)height{
  166. UIFont *temp = [UIFont systemFontOfSize:font];
  167. NSDictionary *attributes = @{NSFontAttributeName : temp};
  168. CGRect sizeFit = [str boundingRectWithSize:CGSizeMake(height, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
  169. return sizeFit.size.height;
  170. }
  171. +(BOOL)isiPhoneX{
  172. struct utsname systemInfo;
  173. uname(&systemInfo);
  174. NSString * deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
  175. if ([deviceString containsString:@"iPhone10"]) {
  176. return YES;
  177. }else{
  178. return NO;
  179. }
  180. }

LCBluetoothManager

  1. #import "LCBluetoothManager.h"
  2. #import "CommonUtils.h"
  3. #import "Account.h"
  4. #import "Home.h"
  5. #import "LocationManager.h"
  6. typedef NS_ENUM(NSInteger,BLEWriteStatus){
  7. WriteOpen = 0,
  8. WriteQuery,
  9. NormalStaus
  10. };
  11. BOOL IsBlueToothOpen = NO;
  12. @interface LCBluetoothManager ()<CBCentralManagerDelegate,CBPeripheralDelegate>
  13. @property (nonatomic,strong) CBPeripheral *peripheral;
  14. @property (nonatomic,strong) CBCentralManager *centralManager;
  15. @property (nonatomic,strong) CBCharacteristic *characteristic;
  16. @property (nonatomic,assign) BLEWriteStatus writeStatus;
  17. @property (nonatomic,strong) NSTimer *timer;
  18. @property (nonatomic) BOOL isSendCancle;
  19. @end
  20. @implementation LCBluetoothManager
  21. +(instancetype)sharedManager{
  22. static LCBluetoothManager *sharedManager;
  23. static dispatch_once_t onceToken;
  24. dispatch_once(&onceToken, ^{
  25. sharedManager = [[self alloc] init];
  26. });
  27. return sharedManager;
  28. }
  29. + (BOOL)isBlueOpen
  30. {
  31. return IsBlueToothOpen;
  32. }
  33. -(instancetype)init{
  34. if (self == [super init]) {
  35. _writeStatus = NormalStaus;
  36. }
  37. return self;
  38. }
  39. //开锁
  40. -(void)openLock{
  41. _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
  42. _writeStatus = NormalStaus;
  43. }
  44. //连接指定车锁
  45. -(void)connectBTEWtihLockNo:(NSString *)lockNo{
  46. //请求开锁密钥
  47. // [self.centralManager cancelPeripheralConnection:_peripheral];
  48. _lockno = lockNo;
  49. [self openLock];
  50. }
  51. -(void)cancelPeripheralConnection{
  52. if (_peripheral) {
  53. _conectedState = DisconnectStateWithCancle;
  54. [self.centralManager cancelPeripheralConnection:_peripheral];
  55. }
  56. }
  57. //请求服务器是否开锁成功
  58. - (void)checkRent{
  59. NSString *url = [kBaseUrl stringByAppendingPathComponent:kCheckRent];
  60. NSString *SIGN = [CommonUtils getSign];
  61. NSString *AUTH = [Account shareAccount].user.auth;
  62. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  63. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  64. [manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];
  65. [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  66. [formData appendPartWithFormData:[_rentid dataUsingEncoding:NSUTF8StringEncoding] name:@"rentid"];
  67. [formData appendPartWithFormData:[_lockno dataUsingEncoding:NSUTF8StringEncoding] name:@"lockno"];
  68. [formData appendPartWithFormData:[_rentposition dataUsingEncoding:NSUTF8StringEncoding] name:@"rentposition"];
  69. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  70. NSLog(@"%@",responseObject);
  71. NSString *status = responseObject[@"status"];
  72. NSString *msg = responseObject[@"msg"];
  73. if ([status integerValue] == 1) {
  74. [[NSNotificationCenter defaultCenter] postNotificationName:kOpenLockSuccess object:nil];
  75. //开始记录轨迹
  76. [[LocationManager sharedLocationManager] startSaveRoute];
  77. }else{
  78. }
  79. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  80. NSLog(@"%@",error);
  81. }];
  82. }
  83. #pragma mark CoreBluetoothDelegate
  84. //外设
  85. //中心设备
  86. - (void)centralManagerDidUpdateState:(CBCentralManager *)central{
  87. switch (central.state) {
  88. case CBCentralManagerStatePoweredOn:
  89. {
  90. IsBlueToothOpen = YES;
  91. //扫描外设(discover)
  92. NSLog(@"蓝牙可用");
  93. // 根据SERVICE_UUID来扫描外设,如果不设置SERVICE_UUID,则扫描所有蓝牙设备
  94. // [_centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:SERVICES_UUID]] options:nil];
  95. //34AD9190-6055-28BB-B916-87A805513A66
  96. CBUUID *uuid = [CBUUID UUIDWithString:@"34AD9190-6055-28BB-B916-87A805513A66"];
  97. if (_lockno) {
  98. [central scanForPeripheralsWithServices:nil options:nil];
  99. }
  100. }
  101. break;
  102. default:
  103. [CommonUtils showTextHudModeWithInfo:@"蓝牙连接断开" view:[UIApplication sharedApplication].keyWindow.rootViewController.view stayTime:1.0];
  104. _conectedState = DisconnectStateWithNoCancle;
  105. break;
  106. }
  107. }
  108. /** 发现符合要求的外设,回调 */
  109. - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
  110. // 对外设对象进行强引用
  111. NSLog(@"当扫描到设备:%@",peripheral.name);
  112. //10秒钟扫描不到设备 停止扫描
  113. if (_timer == nil) {
  114. _timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(cancelScan) userInfo:nil repeats:NO];
  115. }
  116. if ([peripheral.name isEqualToString:[NSString stringWithFormat:@"DB%@",_lockno]]) {
  117. self.peripheral = peripheral;
  118. [_centralManager cancelPeripheralConnection:peripheral];
  119. [_centralManager connectPeripheral:self.peripheral options:nil];
  120. }
  121. }
  122. - (void)cancelScan{
  123. // [_centralManager stopScan];
  124. [[NSNotificationCenter defaultCenter] postNotificationName:kStopScap object:nil];
  125. [_timer invalidate];
  126. _timer = nil;
  127. [CommonUtils showTextHudModeWithInfo:@"扫描不到可用蓝牙信息" view:[UIApplication sharedApplication].keyWindow.rootViewController.view stayTime:1.5];
  128. }
  129. /** 连接成功 */
  130. - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
  131. // 可以停止扫描
  132. [self.centralManager stopScan];
  133. // 设置代理
  134. self.peripheral.delegate = self;
  135. // 根据UUID来寻找服务
  136. // _peripheral whri
  137. _peripheral = peripheral;
  138. [_peripheral discoverServices:@[[CBUUID UUIDWithString:@"1960"]]];
  139. _conectedState = ConnectedState;
  140. NSLog(@"连接成功");
  141. }
  142. /** 连接失败的回调 */
  143. -(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
  144. NSLog(@"连接失败");
  145. //定时重连
  146. _conectedState = DisconnectStateWithNoCancle;
  147. }
  148. /** 断开连接 */
  149. - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error {
  150. NSLog(@"断开连接");
  151. if (_conectedState == DisconnectStateWithNoCancle) {//非正常取消连接
  152. [CommonUtils showTextHudModeWithInfo:@"蓝牙连接断开" view:[UIApplication sharedApplication].keyWindow.rootViewController.view stayTime:1.0];
  153. //重连机制
  154. if (_peripheral) {
  155. [central connectPeripheral:peripheral options:nil];
  156. }
  157. }else{//正常取消连接
  158. _lockno = nil;
  159. _conectedState = DisconnectStateWithCancle;
  160. }
  161. }
  162. /** 发现服务 */
  163. - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
  164. // 遍历出外设中所有的服务
  165. for (CBService *service in peripheral.services) {
  166. NSLog(@"所有的服务uuid:%@",service.UUID);
  167. if ([service.UUID.UUIDString isEqual:@"1960"]) {
  168. // [_peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:WRITE_UUID]] forService:service];
  169. [peripheral discoverCharacteristics:nil forService:service];
  170. }
  171. }
  172. }
  173. /** 发现特征回调 */
  174. - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
  175. // 遍历出所需要的特征
  176. for (CBCharacteristic *characteristic in service.characteristics) {
  177. if ([characteristic.UUID.UUIDString isEqual:@"2BB2"]){
  178. [peripheral setNotifyValue:YES forCharacteristic:characteristic];
  179. [peripheral discoverDescriptorsForCharacteristic:characteristic];
  180. }
  181. }
  182. for (CBCharacteristic *characteristic in service.characteristics) {
  183. NSLog(@"所有特征:%@", characteristic.UUID);
  184. if ([characteristic.UUID.UUIDString isEqual:@"2BB1"]) {
  185. _characteristic = characteristic;
  186. ;
  187. if (_isReconnected || _conectedState == DisconnectStateWithNoCancle) {//查询是否关锁
  188. // [_peripheral writeValue:[@"0100" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
  189. //aa0200000001dd544a000000000000000000c055
  190. NSString *queryKey = [[NSUserDefaults standardUserDefaults] objectForKey:kQuerykey];
  191. NSData *data = [self convertHexStrToData:queryKey];
  192. [_peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
  193. [_peripheral readValueForCharacteristic:self.characteristic];
  194. _writeStatus = WriteQuery;
  195. }else if(_secretkey){
  196. NSData *data = [self convertHexStrToData:_secretkey];
  197. [_peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
  198. _writeStatus = WriteOpen;
  199. [_peripheral readValueForCharacteristic:self.characteristic];
  200. }
  201. }else{
  202. [peripheral setNotifyValue:YES forCharacteristic:characteristic];
  203. }
  204. }
  205. }
  206. -(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
  207. //打印出Characteristic和他的Descriptors
  208. NSLog(@"characteristic uuid:%@",characteristic.UUID);
  209. for (CBDescriptor *d in characteristic.descriptors) {
  210. NSLog(@"Descriptor uuid:%@",d.UUID);
  211. // [peripheral setNotifyValue:YES forCharacteristic:characteristic];
  212. // [peripheral writeValue:[@"0100" dataUsingEncoding:NSUTF8StringEncoding] forDescriptor:d];
  213. }
  214. }
  215. /** 订阅状态的改变 */
  216. -(void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
  217. NSLog(@"111");
  218. if (error) {
  219. NSLog(@"订阅失败");
  220. NSLog(@"%@",error);
  221. }
  222. if (characteristic.isNotifying) {
  223. NSLog(@"订阅成功");
  224. } else {
  225. NSLog(@"取消订阅");
  226. }
  227. }
  228. /** 接收到数据回调 */
  229. - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
  230. // 拿到外设发送过来的数据
  231. NSData *data = characteristic.value;
  232. NSString *str = [self convertDataToHexStr:data];
  233. //aa01000000057e63a6000000000000000000bf55 开锁成功
  234. //aa1f405010000000057e63a6000000000000a155 关锁
  235. NSLog(@"蓝牙返回的数据:%@ 特征:%@",str,characteristic.UUID);
  236. // NSString *openLockStr = [str substringWithRange:NSMakeRange(2, 2)];
  237. if ([characteristic.UUID.UUIDString isEqual:@"2BB2"]) {
  238. switch (_writeStatus) {
  239. case WriteOpen:
  240. //向蓝牙发送开锁命令后收到的回掉数据
  241. {
  242. _writeStatus = NormalStaus;
  243. NSString *openLockStr = [str substringWithRange:NSMakeRange(8, 2)];
  244. if ([openLockStr isEqualToString:@"01"]) {
  245. //向锁发送查询命令
  246. [self checkRent];
  247. }
  248. }
  249. break;
  250. case WriteQuery:
  251. // 向蓝牙发送查询命令后收到的回掉数据
  252. {
  253. _isReconnected = NO;
  254. _writeStatus = NormalStaus;
  255. NSString *queryStr = [str substringWithRange:NSMakeRange(24, 2)];
  256. if ([queryStr isEqualToString:@"01"]) {
  257. //蓝牙回应:已开锁
  258. }else{
  259. [[NSNotificationCenter defaultCenter] postNotificationName:kCloseLock object:nil userInfo:@{@"rentid":_rentid,@"lockno":_lockno}];
  260. }
  261. }
  262. break;
  263. case NormalStaus:
  264. //未向蓝牙发送任何数据,收到蓝牙回调数据,用户主动关锁,会回调此处
  265. {
  266. NSString *closeLockStr = [str substringWithRange:NSMakeRange(7, 2)];
  267. if ([closeLockStr isEqualToString:@"01"]) {
  268. //关锁成功
  269. [[NSNotificationCenter defaultCenter] postNotificationName:kCloseLock object:nil userInfo:@{@"rentid":_rentid,@"lockno":_lockno}];
  270. }
  271. }
  272. break;
  273. default:
  274. break;
  275. }
  276. }
  277. }
  278. /** 写入数据回调 */
  279. - (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error {
  280. if (error) {
  281. NSLog(@"写入失败");
  282. }else{
  283. NSLog(@"写入成功");
  284. }
  285. }
  286. - (NSString *)convertDataToHexStr:(NSData *)data {
  287. if (!data || [data length] == 0) {
  288. return @"";
  289. }
  290. NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
  291. [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
  292. unsigned char *dataBytes = (unsigned char*)bytes;
  293. for (NSInteger i = 0; i < byteRange.length; i++) {
  294. NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
  295. if ([hexStr length] == 2) {
  296. [string appendString:hexStr];
  297. } else {
  298. [string appendFormat:@"0%@", hexStr];
  299. }
  300. }
  301. }]
  302. return string;
  303. }
  304. - (NSMutableData *)convertHexStrToData:(NSString *)str {
  305. if (!str || [str length] == 0) {
  306. return nil;
  307. }
  308. NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
  309. NSRange range;
  310. if ([str length] %2 == 0) {
  311. range = NSMakeRange(0,2);
  312. } else {
  313. range = NSMakeRange(0,1);
  314. }
  315. for (NSInteger i = range.location; i < [str length]; i += 2) {
  316. unsigned int anInt;
  317. NSString *hexCharStr = [str substringWithRange:range];
  318. NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
  319. [scanner scanHexInt:&anInt];
  320. NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
  321. [hexData appendData:entity];
  322. range.location += range.length;
  323. range.length = 2;
  324. }
  325. return hexData;
  326. }

#

  1. import "UserTableViewController.h"
  2. #import "BabyFooterViewController.h"
  3. #import "Account.h"
  4. #import "MallCollectionViewController.h"
  5. #import "SettingTableViewController.h"
  6. #import "WebViewController.h"
  7. #import "MessageTableViewController.h"
  8. @interface UserTableViewController ()
  9. @property (weak, nonatomic) IBOutlet UITableViewCell *walletCell;
  10. @property (nonatomic,strong) UIView *topView;
  11. @property (weak, nonatomic) IBOutlet UIView *view1;
  12. @property (weak, nonatomic) IBOutlet UIView *view2;
  13. @property (weak, nonatomic) IBOutlet UILabel *useCount;
  14. @property (weak, nonatomic) IBOutlet UILabel *credit;
  15. @property (weak, nonatomic) IBOutlet UIView *headView;
  16. @property (weak, nonatomic) IBOutlet UILabel *userName;
  17. @property (weak, nonatomic) IBOutlet NSLayoutConstraint *headViewHeight;
  18. @end
  19. @implementation UserTableViewController
  20. - (void)viewDidLoad {
  21. [super viewDidLoad];
  22. }
  23. -(void)viewWillAppear:(BOOL)animated{
  24. [super viewWillAppear:animated];
  25. self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor]};
  26. [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
  27. [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
  28. [self setUpNav];
  29. if ([CommonUtils isiPhoneX]) {
  30. _headViewHeight.constant = 90+30;
  31. }else{
  32. _headViewHeight.constant = 90;
  33. }
  34. [self drawColor];
  35. [self setUpTableview];
  36. [self setUpUserInfo];
  37. }
  38. -(void)viewWillDisappear:(BOOL)animated{
  39. [super viewWillDisappear:animated];
  40. self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor]};
  41. [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:0];
  42. [self.navigationController.navigationBar setShadowImage:nil];
  43. }
  44. -(void)viewDidDisappear:(BOOL)animated{
  45. [super viewDidDisappear:animated];
  46. }
  47. - (void)setUpUserInfo{
  48. _userName.text = [[Account shareAccount].user.mobile stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
  49. }
  50. - (void)setUpTableview{
  51. _walletCell.detailTextLabel.text = [NSString stringWithFormat:@"%.f 元",[[Account shareAccount].user.money floatValue]/100];
  52. self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  53. self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
  54. self.tableView.scrollEnabled =NO;
  55. self.automaticallyAdjustsScrollViewInsets = NO;
  56. // self.tableView.contentInset = UIEdgeInsetsMake(-70, 0, 0, 0);
  57. }
  58. - (void)drawColor{
  59. CAGradientLayer *gradientLayer = [CAGradientLayer layer];
  60. UIColor *beginColor = [UIColor colorWithRed:210.f/255.f green:20/255.f blue:25.f/255.f alpha:1];
  61. UIColor *endColor = [UIColor colorWithRed:240.f/255.f green:130.f/255.f blue:45.f/255.f alpha:1];
  62. gradientLayer.colors = @[(__bridge id)beginColor.CGColor, (__bridge id)endColor.CGColor];
  63. gradientLayer.locations = @[@0.1,@1.0];
  64. gradientLayer.startPoint = CGPointMake(0, 0);
  65. gradientLayer.endPoint = CGPointMake(1.0, 0);
  66. gradientLayer.frame = CGRectMake(0, 0, kScreenW, _headViewHeight.constant);
  67. [self.headView.layer addSublayer:gradientLayer];
  68. }
  69. - (void)setUpNav{
  70. self.navigationController.navigationBar.hidden = NO;
  71. self.title = @"个人中心";
  72. UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
  73. left.image = [UIImage imageNamed:@"back"];
  74. left.tintColor = [UIColor whiteColor];
  75. self.navigationItem.leftBarButtonItem = left;
  76. UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(setting)];
  77. right.image = [UIImage imageNamed:@"设置"];
  78. right.tintColor = [UIColor whiteColor];
  79. self.navigationItem.rightBarButtonItem = right;
  80. ;
  81. }
  82. - (void)setting{
  83. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"User" bundle:[NSBundle mainBundle]];
  84. SettingTableViewController *vc = [sb instantiateViewControllerWithIdentifier:@"setting"];
  85. [self.navigationController pushViewController:vc animated:YES];
  86. }
  87. - (void)close{
  88. [self.navigationController popViewControllerAnimated:YES];
  89. }

BabyFooterViewController

  1. #import "BabyFooterViewController.h"
  2. #import "BabyFooterFirstTableViewCell.h"
  3. #import "BabyFootSecondTableViewCell.h"
  4. #import "FooterViewController.h"
  5. #import "Home.h"
  6. #import <MAMapKit/MAMapKit.h>
  7. #import "Recommend.h"
  8. #import "LocationManager.h"
  9. @interface BabyFooterViewController ()<UITableViewDelegate,UITableViewDataSource>
  10. @property (weak, nonatomic) IBOutlet UITableView *tableView;
  11. @property (nonatomic,strong) Recommend *recommendData;
  12. @end
  13. @implementation BabyFooterViewController
  14. - (void)viewDidLoad {
  15. [super viewDidLoad];
  16. [self setUpTableView];
  17. [self setUpNav];
  18. [self requesData];
  19. }
  20. - (void)setUpNav{
  21. self.navigationController.navigationBar.hidden = NO;
  22. self.title = @"宝宝足迹";
  23. UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
  24. left.image = [UIImage imageNamed:@"back"];
  25. left.tintColor = [UIColor blackColor];
  26. self.navigationItem.leftBarButtonItem = left;
  27. }
  28. - (void)requesData{
  29. [CommonUtils showLoadingHudWithView:self.view text:nil];
  30. NSString *url = [kBaseUrl stringByAppendingPathComponent:kGetFooterFences];
  31. [CommonUtils sendPOST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  32. NSString *city = [LocationManager sharedLocationManager].loctionInfo.city;
  33. if (city == nil) {
  34. [formData appendPartWithFormData:[@"武汉市" dataUsingEncoding:NSUTF8StringEncoding] name:@"cityName"];
  35. }else{
  36. [formData appendPartWithFormData:[city dataUsingEncoding:NSUTF8StringEncoding] name:@"cityName"];
  37. }
  38. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  39. NSLog(@"%@",responseObject);
  40. NSString *status = responseObject[@"status"];
  41. NSString *msg = responseObject[@"msg"];
  42. [CommonUtils hideHudForView:self.view];
  43. if ([status integerValue] == 1) {
  44. _recommendData = [[Recommend alloc] initRecommend:responseObject[@"data"]];
  45. [self.tableView reloadData];
  46. }else{
  47. [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];
  48. }
  49. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
  50. NSLog(@"%@",error);
  51. [CommonUtils hideHudForView:self.view];
  52. [CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];
  53. }];
  54. }
  55. - (void)close{
  56. [self.navigationController popViewControllerAnimated:YES];
  57. }
  58. - (void)setUpTableView{
  59. [self.tableView registerNib:[UINib nibWithNibName:@"BabyFooterFirstTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"BabyFooterFirstTableViewCell"];
  60. [self.tableView registerNib:[UINib nibWithNibName:@"BabyFootSecondTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"BabyFootSecondTableViewCell"];
  61. self.tableView.delegate = self;
  62. self.tableView.dataSource = self;
  63. self.tableView.estimatedRowHeight = 0;
  64. self.tableView.estimatedSectionHeaderHeight = 0;
  65. self.tableView.estimatedSectionFooterHeight = 0;
  66. // self.tableView.dataSource = self;
  67. self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectNull];
  68. }
  69. - (void)skipMoreFooter{
  70. }
  71. - (void)didReceiveMemoryWarning {
  72. [super didReceiveMemoryWarning];
  73. // Dispose of any resources that can be recreated.
  74. }
  75. #pragma mark - Table view data source
  76. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  77. return 2;
  78. }
  79. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  80. switch (section) {
  81. case 0:
  82. return _recommendData.footArr.count;
  83. break;
  84. case 1:
  85. return _recommendData.fenceArr.count;
  86. break;
  87. default:
  88. return 0;
  89. break;
  90. }
  91. }
  92. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  93. switch (indexPath.section) {
  94. case 0:
  95. return 120;
  96. break;
  97. case 1:
  98. return 120;
  99. break;
  100. default:
  101. return 0;
  102. break;
  103. }
  104. }
  105. -(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
  106. return 0.1;
  107. }
  108. -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
  109. switch (section) {
  110. case 0:
  111. return 10;
  112. break;
  113. default:
  114. return 0;
  115. break;
  116. }
  117. }
  118. - (NSString *)getTimeStrWithTimetap:(NSString *)timetamp{
  119. NSDateFormatter *stampFormatter = [[NSDateFormatter alloc] init];
  120. [stampFormatter setDateFormat:@"YYYY-MM-dd HH:mm"];
  121. //以 1970/01/01 GMT为基准,然后过了secs秒的时间
  122. NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timetamp integerValue]/1000];
  123. NSString *timeStr = [stampFormatter stringFromDate:date];
  124. return timeStr;
  125. }
  126. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  127. if (indexPath.section == 0) {
  128. BabyFooterFirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BabyFooterFirstTableViewCell" forIndexPath:indexPath];
  129. cell.backView.layer.borderWidth = 1;
  130. cell.backView.layer.borderColor = [UIColor blackColor].CGColor;
  131. cell.backView.layer.cornerRadius = 3;
  132. cell.clipsToBounds = YES;
  133. cell.selectionStyle = UITableViewCellSelectionStyleNone;
  134. cell.separatorInset = UIEdgeInsetsMake(0, kScreenW, 0, 0);
  135. cell.address.text = _recommendData.footArr[indexPath.row].address;
  136. //时间
  137. NSString *startTime = [self getTimeStrWithTimetap:_recommendData.footArr[indexPath.row].renttime];
  138. NSString *rturnTime = [self getTimeStrWithTimetap:_recommendData.footArr[indexPath.row].returntime];
  139. cell.time.text = [NSString stringWithFormat:@"%@~%@",startTime,rturnTime];
  140. return cell;
  141. }else{
  142. BabyFootSecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BabyFootSecondTableViewCell" forIndexPath:indexPath];
  143. cell.selectionStyle = UITableViewCellSelectionStyleNone;
  144. cell.name.text = _recommendData.fenceArr[indexPath.row].name;
  145. cell.address.text =[NSString stringWithFormat:@"%@ %@",_recommendData.fenceArr[indexPath.row].address,_recommendData.fenceArr[indexPath.row].describe];
  146. cell.lockCount.text = [NSString stringWithFormat:@"剩余%@辆",_recommendData.fenceArr[indexPath.row].lockCount];
  147. MAMapPoint point1 = MAMapPointForCoordinate(CLLocationCoordinate2DMake([LocationManager sharedLocationManager].latitude,[LocationManager sharedLocationManager].longitude));
  148. MAMapPoint point2 = MAMapPointForCoordinate(CLLocationCoordinate2DMake([_recommendData.fenceArr[indexPath.row].latitude floatValue],[_recommendData.fenceArr[indexPath.row].longitude floatValue]));
  149. //2.计算距离
  150. CLLocationDistance distance = MAMetersBetweenMapPoints(point1,point2)/1000.f;
  151. cell.distance.text = [NSString stringWithFormat:@"%.2fkm",distance];
  152. return cell;
  153. }
  154. }
  155. //-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
  156. //// if (section == 1 && _recommendData != nil) {
  157. //// UIView *head = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 30)];
  158. //// head.backgroundColor = [UIColor groupTableViewBackgroundColor];
  159. //// UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
  160. //// btn.frame = CGRectMake(kScreenW-60,0 , 60, 30);
  161. //// [btn setTitle:@"更多" forState:UIControlStateNormal];
  162. //// [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  163. //// btn.titleLabel.font = [UIFont systemFontOfSize:14];
  164. //// [btn addTarget:self action:@selector(skipMoreFooter) forControlEvents:UIControlEventTouchUpInside];
  165. //// [head addSubview:btn];
  166. //// return head;
  167. //// }
  168. // UIView *head = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 30)];
  169. // head.backgroundColor = [UIColor groupTableViewBackgroundColor];
  170. // UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
  171. // [head addSubview:titleLab];
  172. // titleLab.font = [UIFont systemFontOfSize:13];
  173. // titleLab.textColor = [UIColor blackColor];
  174. //
  175. // if (section == 0) {
  176. // titleLab.text = @"宝贝行程";
  177. // }else{
  178. // titleLab.text = @"商圈推荐";
  179. // }
  180. // return head;
  181. //}
  182. -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  183. switch (indexPath.section) {
  184. case 0:
  185. {
  186. UIStoryboard *sb = [UIStoryboard storyboardWithName:@"User" bundle:[NSBundle mainBundle]];
  187. FooterViewController *vc = [sb instantiateViewControllerWithIdentifier:@"babyFooter"];
  188. vc.rentId = _recommendData.footArr[indexPath.row].rentid;
  189. [self.navigationController pushViewController:vc animated:YES];
  190. }
  191. break;
  192. default:
  193. break;
  194. }
  195. }
  196. - (void)scrollViewDidScroll:(UIScrollView *)scrollView{
  197. CGFloat sectionHeaderHeight = 30;//设置你footer高度
  198. if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
  199. scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
  200. } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
  201. scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
  202. }
  203. }

  1. #import "RechargeViewController.h"
  2. #import "CommonUtils.h"
  3. #import "Pay.h"
  4. #import "Account.h"
  5. #import "Recharge.h"
  6. #import <AlipaySDK/AlipaySDK.h>
  7. #import "WXApiObject.h"
  8. #import "WXApi.h"
  9. #import "WebViewController.h"
  10. @interface RechargeViewController ()
  11. @property (weak, nonatomic) IBOutlet UIView *AlView;
  12. @property (weak, nonatomic) IBOutlet UIView *WXView;
  13. @property (weak, nonatomic) IBOutlet UIImageView *ALSelect;
  14. @property (weak, nonatomic) IBOutlet UIImageView *WXSelect;
  15. @property (nonatomic) BOOL isALPay;
  16. @property (weak, nonatomic) IBOutlet UIButton *btn1;
  17. @property (weak, nonatomic) IBOutlet UIButton *btn2;
  18. @property (weak, nonatomic) IBOutlet UIButton *btn3;
  19. @property (weak, nonatomic) IBOutlet UIButton *btn4;
  20. @property (weak, nonatomic) IBOutlet UIButton *btn5;
  21. @property (nonatomic,strong) NSString *payCount;
  22. @property (weak, nonatomic) IBOutlet UIView *coverView;
  23. @property (weak, nonatomic) IBOutlet UIView *rechargeView;
  24. @property (weak, nonatomic) IBOutlet NSLayoutConstraint *rechargeViewHeight;
  25. @property (nonatomic,strong) NSMutableArray <Recharge *> *rechargeArr;
  26. @property (nonatomic,strong) NSMutableArray *rechargeBtnArr;
  27. @property (nonatomic,strong) NSString *rechargeid;
  28. @end
  29. #define kRechargeBtnH 50
  30. #define kRechargeBtnW ([UIScreen mainScreen].bounds.size.width - 24)/2
  31. @implementation RechargeViewController
  32. - (void)viewDidLoad {
  33. [super viewDidLoad];
  34. [self setUpNav];
  35. UITapGestureRecognizer *tapGestureRecognizer2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectALPay)];
  36. [_AlView addGestureRecognizer:tapGestureRecognizer2];
  37. _isALPay = YES;
  38. UITapGestureRecognizer *tapGestureRecognizer3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectWXPay)];
  39. [_WXView addGestureRecognizer:tapGestureRecognizer3];
  40. [self.view bringSubviewToFront:_coverView];
  41. [self getRecharge];
  42. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tip) name:@"finishWXPay" object:nil];
  43. }
  44. - (void)tip{
  45. [CommonUtils showTextHudModeWithInfo:@"充值成功" view:self.view stayTime:1.5];
  46. }
  47. - (void)setUpNav{
  48. self.navigationController.navigationBar.hidden = NO;
  49. self.title = @"充值";
  50. UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
  51. left.image = [UIImage imageNamed:@"back"];
  52. left.tintColor = [UIColor blackColor];
  53. self.navigationItem.leftBarButtonItem = left;
  54. }
  55. - (void)close{
  56. [self.navigationController popViewControllerAnimated:YES];
  57. }
  58. #pragma mark - 网络请求
  59. - (void)getRecharge{
  60. [CommonUtils showLoadingHudModelWithView:self.view handle:nil];
  61. NSString *url = [kBaseUrl stringByAppendingPathComponent:kGetRecharge];
  62. NSString *SIGN = [CommonUtils getSign];
  63. NSString *AUTH = [Account shareAccount].user.auth;
  64. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  65. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  66. [manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];
  67. [manager POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  68. [CommonUtils hideHudForView:self.view];
  69. NSLog(@"%@",responseObject);
  70. NSString *status = responseObject[@"status"];
  71. NSString *msg = responseObject[@"msg"];
  72. if ([status integerValue] == 1) {
  73. _coverView.hidden = YES;
  74. _rechargeArr = [NSMutableArray array];
  75. for (NSDictionary *dict in responseObject[@"data"]) {
  76. Recharge *recharge = [[Recharge alloc] initRecharge:dict];
  77. [_rechargeArr addObject:recharge];
  78. }
  79. _rechargeid = [NSString stringWithFormat:@"%@",_rechargeArr[0].rechageId];
  80. [self layoutRechargeBtnView];
  81. }else{
  82. [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];
  83. }
  84. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  85. [CommonUtils hideHudForView:self.view];
  86. [CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];
  87. }];
  88. }
  89. - (void)layoutRechargeBtnView{
  90. _rechargeViewHeight.constant = (_rechargeArr.count/2 + _rechargeArr.count%2)*(kRechargeBtnH+16)+16;
  91. _rechargeBtnArr = [NSMutableArray array];
  92. for (int i = 0; i < _rechargeArr.count; i++) {
  93. UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
  94. btn.frame = CGRectMake(i%2*(kRechargeBtnW+8)+8, i/2*(kRechargeBtnH+16)+16, kRechargeBtnW, kRechargeBtnH);
  95. btn.layer.cornerRadius = kRechargeBtnH/2;
  96. btn.clipsToBounds = YES;
  97. //背景颜色
  98. if (i == 0) {
  99. btn.backgroundColor = [UIColor colorWithRed:237.f/255.f green:56.f/255.f blue:53.f/255.f alpha:1];
  100. }else{
  101. btn.backgroundColor = [UIColor colorWithRed:242.f/255.f green:242.f/255.f blue:242.f/255.f alpha:1];
  102. }
  103. NSString *btnTitle = [NSString stringWithFormat:@"%.2f元(赠送%.f元)",[_rechargeArr[i].recharge floatValue]/100.f,[_rechargeArr[i].gift floatValue]/100.f];
  104. [btn setTitle:btnTitle forState:UIControlStateNormal];
  105. btn.titleLabel.font = [UIFont systemFontOfSize:14];
  106. [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  107. btn.tag = 100+i;
  108. [btn addTarget:self action:@selector(clickRechargeBtn:) forControlEvents:UIControlEventTouchUpInside];
  109. [_rechargeBtnArr addObject:btn];
  110. [_rechargeView addSubview:btn];
  111. }
  112. }
  113. - (void)clickRechargeBtn:(UIButton *)sender{
  114. for (UIButton *btn in _rechargeBtnArr) {
  115. if (btn.tag == sender.tag) {
  116. btn.backgroundColor = [UIColor colorWithRed:237.f/255.f green:56.f/255.f blue:53.f/255.f alpha:1];;
  117. _rechargeid = [NSString stringWithFormat:@"%@",_rechargeArr[sender.tag-100].rechageId] ;
  118. }else{
  119. btn.backgroundColor = [UIColor colorWithRed:242.f/255.f green:242.f/255.f blue:242.f/255.f alpha:1];
  120. }
  121. }
  122. }
  123. - (IBAction)skipAgreement:(UIButton *)sender {
  124. WebViewController *vc = [[WebViewController alloc] init];
  125. vc.url = @"http://manage.mabaoxc.com/p/notify/getNotify?id=3";
  126. [self.navigationController pushViewController:vc animated:YES];
  127. }
  128. - (IBAction)pay:(UIButton *)sender {
  129. [CommonUtils showLoadingHudModelWithView:self.view handle:nil];
  130. NSString *url = [kBaseUrl stringByAppendingPathComponent:kMemberRecharge];
  131. NSString *SIGN = [CommonUtils getSign];
  132. NSString *AUTH = [Account shareAccount].user.auth;
  133. AFHTTPSessionManager *manager = [CommonUtils getAFHTTPSessionManager];
  134. [manager.requestSerializer setValue:SIGN forHTTPHeaderField:@"SIGN"];
  135. [manager.requestSerializer setValue:AUTH forHTTPHeaderField:@"AUTH"];
  136. [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  137. //参数
  138. NSString *payment;
  139. if (_isALPay) {
  140. payment = @"1";
  141. }else{
  142. payment = @"2";
  143. }
  144. [formData appendPartWithFormData:[payment dataUsingEncoding:NSUTF8StringEncoding] name:@"payment"];
  145. [formData appendPartWithFormData:[_rechargeid dataUsingEncoding:NSUTF8StringEncoding] name:@"rechargeid"];
  146. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  147. NSLog(@"%@",responseObject);
  148. [CommonUtils hideHudForView:self.view];
  149. NSString *status = responseObject[@"status"];
  150. NSString *msg = responseObject[@"msg"];
  151. if ([status integerValue] == 1) {
  152. // 验证成功
  153. if (_isALPay) {
  154. [self AliPay:responseObject];
  155. }else{
  156. [self WXPay:responseObject[@"data"]];
  157. }
  158. }else{
  159. [CommonUtils showTextHudModeWithInfo:msg view:self.view stayTime:1.5];
  160. }
  161. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  162. NSLog(@"%@",error);
  163. [CommonUtils hideHudForView:self.view];
  164. [CommonUtils showTextHudModeWithInfo:@"服务器异常" view:self.view stayTime:1.5];
  165. }];
  166. }
  167. - (void)AliPay:(NSDictionary *)responseObject{
  168. //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
  169. NSString *appScheme = @"mengbei";
  170. // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
  171. NSString *orderString = responseObject[@"data"];
  172. // NOTE: 调用支付结果开始支付
  173. [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
  174. NSLog(@"reslut = %@",resultDic);
  175. NSString *statusCode = resultDic[@"resultStatus"];
  176. if ([statusCode isEqual:@"9000"]) {//
  177. //关闭页面
  178. dispatch_async(dispatch_get_main_queue(), ^{
  179. [CommonUtils showTextHudModeWithInfo:@"充值成功" view:self.view stayTime:1.5];
  180. });
  181. }else{
  182. dispatch_async(dispatch_get_main_queue(), ^{
  183. [CommonUtils showTextHudModeWithInfo:@"支付失败" view:self.view stayTime:1.5];
  184. });
  185. }
  186. }];
  187. }
  188. - (void)WXPay:(NSDictionary *)responseObject{
  189. PayReq *request = [[PayReq alloc] init] ;
  190. request.partnerId = responseObject[@"partnerid"];
  191. request.prepayId= responseObject[@"prepayid"];
  192. request.package = @"Sign=WXPay";
  193. request.nonceStr= responseObject[@"noncestr"];
  194. request.timeStamp= [responseObject[@"timestamp"] intValue];
  195. request.sign= responseObject[@"sign"];
  196. BOOL success = [WXApi sendReq:request];
  197. }
  198. - (void)selectALPay{
  199. _ALSelect.image = [UIImage imageNamed:@"withdraw_success"];
  200. _WXSelect.image = [UIImage imageNamed:@"Unchecked"];
  201. _isALPay = YES;
  202. }
  203. - (void)selectWXPay{
  204. _ALSelect.image = [UIImage imageNamed:@"Unchecked"];
  205. _WXSelect.image = [UIImage imageNamed:@"withdraw_success"];
  206. _isALPay = NO;
  207. }
  208. - (void)didReceiveMemoryWarning {
  209. [super didReceiveMemoryWarning];
  210. // Dispose of any resources that can be recreated.
  211. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注