car in 場站查車鎖車 ios
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

286 行
12KB

  1. //
  2. // InquireCarViewController.m
  3. // goodpk
  4. //
  5. // Created by 歐特儀 on 2020/2/11.
  6. // Copyright © 2020 Altob. All rights reserved.
  7. //
  8. #import "InquireCarViewController.h"
  9. #import "InquireCarModel.h"
  10. #import "CocoaSecurity.h"
  11. #import "Util.h"
  12. #import <CommonCrypto/CommonDigest.h>
  13. #define APIURL @"https://cloudservice.altob.com.tw/LockCarSerivce/api/JumpApi"
  14. #define CARWHERE @"/CARWHERE?carNo="
  15. #define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
  16. @interface InquireCarViewController ()<UITextFieldDelegate>
  17. @property (weak, nonatomic) IBOutlet UIButton *okBtn;
  18. @property (weak, nonatomic) IBOutlet UITextField *inputText;
  19. @property (weak, nonatomic) IBOutlet UIImageView *ImgView;
  20. @property (weak, nonatomic) IBOutlet UILabel *stationName;
  21. @property (weak, nonatomic) IBOutlet UILabel *inTime;
  22. @property (weak, nonatomic) IBOutlet UIView *FootView;
  23. @end
  24. @implementation InquireCarViewController
  25. - (void)viewDidLoad {
  26. [super viewDidLoad];
  27. // Do any additional setup after loading the view.
  28. self.title = @"車輛位置查詢";
  29. [self.okBtn addTarget:self
  30. action:@selector(okButtonClicked:)
  31. forControlEvents:UIControlEventTouchUpInside
  32. ];
  33. //注册截圖通知
  34. [[NSNotificationCenter defaultCenter] addObserver:self
  35. selector:@selector(userDidTakeScreenshot:)
  36. name:UIApplicationUserDidTakeScreenshotNotification object:nil];
  37. self.inputText.delegate = self;
  38. self.inputText.keyboardType = UIKeyboardTypeASCIICapable;
  39. }
  40. - (BOOL)textField:(UITextField* )textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString* )string
  41. {
  42. if (textField == self.inputText)
  43. {
  44. NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
  45. NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
  46. if([string isEqualToString:filtered]){
  47. NSUInteger newLength = [textField.text length] + [string length] - range.length;
  48. return (newLength > 10 ) ? NO : YES;
  49. }else{
  50. return NO;
  51. }
  52. }
  53. else
  54. {
  55. return true;
  56. }
  57. }
  58. - (void) okButtonClicked:(id)sender {
  59. if([self.inputText.text length] > 0){
  60. [self posCarNo:[self.inputText.text uppercaseStringWithLocale:[NSLocale currentLocale]]];
  61. [[[UIApplication sharedApplication] keyWindow] endEditing: YES];
  62. }else{
  63. [self showAlert:@"錯誤" :@"請輸入車牌" :nil];
  64. }
  65. }
  66. -(void) posCarNo:(NSString*)carNo{
  67. CocoaSecurityResult *NcarNo = [CocoaSecurity aesEncrypt:carNo key:[Util sha256HashFor:@"Altob"]];
  68. NSString *carUrl = [NSString stringWithFormat:@"%@%@%@", APIURL,CARWHERE, NcarNo.base64];
  69. //第一步,创建URL
  70. NSURL *url = [NSURL URLWithString:carUrl];
  71. //NSDictionary *jsonBodyDict = @{};
  72. //第二步,创建请求
  73. NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
  74. //设置请求方式为POST,默认为GET
  75. [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  76. [request setValue:@"Bearer 9a406a82bd551e6ef8e845f42f788af4" forHTTPHeaderField:@"Authorization"];
  77. [request setHTTPMethod:@"GET"];
  78. //设置参数
  79. //NSData *jsonBodyData = [NSJSONSerialization dataWithJSONObject:jsonBodyDict options:kNilOptions error:nil];
  80. //[request setHTTPBody:jsonBodyData];
  81. //新作法
  82. NSURLSession *sesson = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
  83. // 2.创建 NSURLSessionDataTask
  84. NSURLSessionDataTask *dataTask = [sesson dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  85. if (error) {
  86. // error
  87. dispatch_async(dispatch_get_main_queue(), ^{
  88. [self showAlert: @"注意" : @"您所使用的連線加密(SSL)異常,基於安全考量不提供相關功能。請確認您的連線環境及App下載來源安全。" : 0];
  89. });
  90. }else {
  91. // 获得数据后,返回到主线程更新 UI
  92. dispatch_async(dispatch_get_main_queue(), ^{
  93. NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  94. InquireCarModel *ICM = [[InquireCarModel alloc] initWithString:responseString error:nil];
  95. if([ICM.result_code isEqual:@"OK"]){
  96. //NSLog(@"參數查詢:%@", ICM.station_name);
  97. //NSLog(@"參數查詢:%@", ICM.in_time);
  98. //NSLog(@"參數查詢:%@", ICM.image_url);
  99. //顯示UI
  100. [self.FootView setHidden:NO];
  101. //放資料
  102. [self.stationName setText:ICM.station_name];
  103. [self.inTime setText:ICM.in_time];
  104. if(ICM.image_url2 != nil && ![ICM.image_url2 isEqualToString:@""]){
  105. //下載圖片_非同步
  106. dispatch_async(dispatch_get_global_queue(0,0), ^{
  107. NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:ICM.image_url2]];
  108. //NSLog(@"參數查詢:%@", data);
  109. if ( data == nil )
  110. return;
  111. dispatch_async(dispatch_get_main_queue(), ^{
  112. // WARNING: is the cell still using the same data by this point??
  113. self.ImgView.image = [UIImage imageWithData: data];
  114. });
  115. });
  116. }else{
  117. //下載圖片_非同步
  118. dispatch_async(dispatch_get_global_queue(0,0), ^{
  119. NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:ICM.image_url]];
  120. //NSLog(@"參數查詢:%@", data);
  121. if ( data == nil )
  122. return;
  123. dispatch_async(dispatch_get_main_queue(), ^{
  124. // WARNING: is the cell still using the same data by this point??
  125. self.ImgView.image = [UIImage imageWithData: data];
  126. });
  127. });
  128. }
  129. }else {
  130. [self showAlert:@"錯誤" :@"沒有資料,請確認車牌輸入正確或網路連接正常" :nil];
  131. }
  132. });
  133. }
  134. }];
  135. // 3.执行 Task
  136. [dataTask resume];
  137. /*
  138. //第三步,连接服务器
  139. NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
  140. NSString *jsonString = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
  141. //NSLog(@"ticket:%@", jsonString);
  142. InquireCarModel *ICM = [[InquireCarModel alloc] initWithString:jsonString error:nil];
  143. if([ICM.result_code isEqual:@"OK"]){
  144. //NSLog(@"參數查詢:%@", ICM.station_name);
  145. //NSLog(@"參數查詢:%@", ICM.in_time);
  146. //NSLog(@"參數查詢:%@", ICM.image_url);
  147. //顯示UI
  148. [self.FootView setHidden:NO];
  149. //放資料
  150. [self.stationName setText:ICM.station_name];
  151. [self.inTime setText:ICM.in_time];
  152. if(ICM.image_url2 != nil && ![ICM.image_url2 isEqualToString:@""]){
  153. //下載圖片_非同步
  154. dispatch_async(dispatch_get_global_queue(0,0), ^{
  155. NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:ICM.image_url2]];
  156. //NSLog(@"參數查詢:%@", data);
  157. if ( data == nil )
  158. return;
  159. dispatch_async(dispatch_get_main_queue(), ^{
  160. // WARNING: is the cell still using the same data by this point??
  161. self.ImgView.image = [UIImage imageWithData: data];
  162. });
  163. });
  164. }else{
  165. //下載圖片_非同步
  166. dispatch_async(dispatch_get_global_queue(0,0), ^{
  167. NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:ICM.image_url]];
  168. //NSLog(@"參數查詢:%@", data);
  169. if ( data == nil )
  170. return;
  171. dispatch_async(dispatch_get_main_queue(), ^{
  172. // WARNING: is the cell still using the same data by this point??
  173. self.ImgView.image = [UIImage imageWithData: data];
  174. });
  175. });
  176. }
  177. }else {
  178. [self showAlert:@"錯誤" :@"沒有資料,請確認車牌輸入正確或網路連接正常" :nil];
  179. }
  180. */
  181. }
  182. -(void)showAlert:(NSString *)title :(NSString *)text: (NSInteger *)type{
  183. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title
  184. message:text
  185. preferredStyle:UIAlertControllerStyleAlert ];
  186. UIAlertAction *sinupAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
  187. }];
  188. [alertController addAction:sinupAction];
  189. [self presentViewController:alertController animated:YES completion:nil];
  190. }
  191. //截屏响应
  192. - (void)userDidTakeScreenshot:(NSNotification *)notification
  193. {
  194. [self showAlert: @"注意" : @"偵測到截圖,請妥善保管截圖,避免重要資訊外流" : 0];
  195. }
  196. - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler//通过调用block,来告诉NSURLSession要不要收到这个证书
  197. {
  198. // Get remote certificate
  199. SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
  200. SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
  201. SecKeyRef serverPublicKey = SecCertificateCopyPublicKey(certificate);
  202. // Set SSL policies for domain name check
  203. NSMutableArray *policies = [NSMutableArray array];
  204. [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)challenge.protectionSpace.host)];
  205. SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
  206. // Evaluate server certificate
  207. SecTrustResultType result;
  208. SecTrustEvaluate(serverTrust, &result);
  209. BOOL certificateIsValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
  210. // Get local and remote cert data
  211. NSData *remoteCertificateData = CFBridgingRelease(SecCertificateCopyData(certificate));
  212. SecCertificateRef cer = SecCertificateCreateWithData ( NULL, (__bridge CFDataRef) remoteCertificateData);
  213. NSLog(@"%@", cer);
  214. NSString *certPath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"cer"];
  215. NSData *certData = [NSData dataWithContentsOfFile:certPath];
  216. SecCertificateRef localCertificate = SecCertificateCreateWithData(nil, (CFDataRef)certData);
  217. NSLog(@"localCertificate: %@", localCertificate);
  218. NSString *hash = [[self doSha256:remoteCertificateData] base64EncodedStringWithOptions:0];
  219. // The pinnning check
  220. if ([hash isEqualToString:@"FHloZIw4i6+30lmxrUujLieHlIDpxHySL1niMxvgmpU="] && certificateIsValid) {
  221. NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
  222. completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
  223. } else {
  224. completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, NULL);
  225. }
  226. }
  227. - (NSData *)doSha256:(NSData *)dataIn {
  228. NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
  229. CC_SHA256(dataIn.bytes, dataIn.length, macOut.mutableBytes);
  230. return macOut;
  231. }
  232. @end