|
- //
- // LockCarViewController.m
- // goodpk
- //
- // Created by 歐特儀 on 2020/3/20.
- // Copyright © 2020 Altob. All rights reserved.
- //
-
- #import "LockCarViewController.h"
- #import <CommonCrypto/CommonDigest.h>
- #import "LockModel.h"
- #import "CocoaSecurity.h"
- #import "Util.h"
- #import <CommonCrypto/CommonDigest.h>
-
- #define APIURL @"https://cloudservice.altob.com.tw/LockCarSerivce/api/JumpApi"
- #define CARSECURITY @"/CARSECURITY?"
-
- @interface LockCarViewController ()
- @property (weak, nonatomic) IBOutlet UIImageView *Image;
- @property (weak, nonatomic) IBOutlet UIButton *LockBtn;
- @property (weak, nonatomic) IBOutlet UIButton *nLockBtn;
-
- @end
-
- @implementation LockCarViewController
-
- - (void)viewDidLoad {
- [super viewDidLoad];
- // Do any additional setup after loading the view.
- //NSLog(@"傳值:%@", self.status);
- //NSLog(@"傳值:%@", self.acct);
- //NSLog(@"傳值:%@", self.pwd);
-
- if([self.status containsString:@"unlocked"]){
- self.nLockBtn.userInteractionEnabled = NO;
- self.nLockBtn.alpha = 0.4;
- }else{
- self.LockBtn.userInteractionEnabled = NO;
- self.LockBtn.alpha = 0.4;
- self.Image.image = [UIImage imageNamed:@"Lock_on"];
- }
-
- [self.LockBtn setTag:0];
- [self.nLockBtn setTag:1];
-
- [self.LockBtn addTarget:self
- action:@selector(handleButtonClicked:)
- forControlEvents:UIControlEventTouchUpInside
- ];
-
- [self.nLockBtn addTarget:self
- action:@selector(handleButtonClicked:)
- forControlEvents:UIControlEventTouchUpInside
- ];
- }
-
- - (void) handleButtonClicked:(id)sender {
- switch ([sender tag]) {
- case 0:
- //API 鎖車
- [self Lock_api:self.acct :self.pwd];
- break;
- case 1:
- //API 解鎖
- [self nLock_api:self.acct :self.pwd];
- break;
- }
- }
-
- //鎖車
- -(void) Lock_api:(NSString *)acct :(NSString *)pwd {
-
- CocoaSecurityResult *Nacct = [CocoaSecurity aesEncrypt:acct key:[Util sha256HashFor:@"Altob"]];
- NSString *status = @"1";
- //NSLog(@"加密字串:%@", [NSString stringWithFormat:@"%@%@%@%@%@", acct, @"i", pwd, @"iii", status]);
- NSString *key = [self md5: [NSString stringWithFormat:@"%@%@%@%@%@", acct, @"i", pwd, @"iii", status]];
- NSString *carUrl = [NSString stringWithFormat:@"%@%@acct=%@&pwd=%@&status=%@&key=%@&station=%@", APIURL, CARSECURITY, Nacct.base64, pwd, status, key, self.station];
-
- //第一步,创建URL
- NSURL *url = [NSURL URLWithString:carUrl];
- //NSDictionary *jsonBodyDict = @{};
-
- //NSLog(@"URL: %@", url);
-
- //第二步,创建请求
- NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
- //设置请求方式为POST,默认为GET
- [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
- [request setValue:@"Bearer 9a406a82bd551e6ef8e845f42f788af4" forHTTPHeaderField:@"Authorization"];
- [request setHTTPMethod:@"GET"];
-
- //设置参数
- //NSData *jsonBodyData = [NSJSONSerialization dataWithJSONObject:jsonBodyDict options:kNilOptions error:nil];
- //[request setHTTPBody:jsonBodyData];
-
- //新作法
- NSURLSession *sesson = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
-
- // 2.创建 NSURLSessionDataTask
- NSURLSessionDataTask *dataTask = [sesson dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
- if (error) {
- // error
- dispatch_async(dispatch_get_main_queue(), ^{
- [self showAlert: @"注意" : @"您所使用的連線加密(SSL)異常,基於安全考量不提供相關功能。請確認您的連線環境及App下載來源安全。" : 0];
- });
- }else {
- // 获得数据后,返回到主线程更新 UI
- dispatch_async(dispatch_get_main_queue(), ^{
- NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
- LockModel *LK= [[LockModel alloc] initWithString:responseString error:nil];
- if([LK.result_code isEqual:@"OK"]){
-
- self.LockBtn.userInteractionEnabled = NO;
- self.LockBtn.alpha = 0.4;
- self.Image.image = [UIImage imageNamed:@"Lock_on"];
-
- self.nLockBtn.userInteractionEnabled = YES;
- self.nLockBtn.alpha = 1;
-
- }else{
- [self showAlert:@"錯誤" :@"鎖車失敗,請稍後再試" :nil];
- }
- });
- }
- }];
- // 3.执行 Task
- [dataTask resume];
-
- /*
- //第三步,连接服务器
- NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
-
- NSString *jsonString = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
- //NSLog(@"CAR LOGIN:%@", jsonString);
-
- LockModel *LK= [[LockModel alloc] initWithString:jsonString error:nil];
- if([LK.result_code isEqual:@"OK"]){
-
- self.LockBtn.userInteractionEnabled = NO;
- self.LockBtn.alpha = 0.4;
- self.Image.image = [UIImage imageNamed:@"Lock_on"];
-
- self.nLockBtn.userInteractionEnabled = YES;
- self.nLockBtn.alpha = 1;
-
- }else{
- [self showAlert:@"錯誤" :@"鎖車失敗,請稍後再試" :nil];
- }
- */
- }
-
- //解鎖
- -(void) nLock_api:(NSString *)acct :(NSString *)pwd {
-
- CocoaSecurityResult *Nacct = [CocoaSecurity aesEncrypt:acct key:[Util sha256HashFor:@"Altob"]];
- NSString *status = @"0";
- //NSLog(@"加密字串:%@", [NSString stringWithFormat:@"%@%@%@%@%@", acct, @"i", pwd, @"iii", status]);
- NSString *key = [self md5: [NSString stringWithFormat:@"%@%@%@%@%@", acct, @"i", pwd, @"iii", status]];
- NSString *carUrl = [NSString stringWithFormat:@"%@%@acct=%@&pwd=%@&status=%@&key=%@&station=%@", APIURL, CARSECURITY, Nacct.base64, pwd, status, key, self.station];
-
- //第一步,创建URL
- NSURL *url = [NSURL URLWithString:carUrl];
- //NSDictionary *jsonBodyDict = @{};
-
- //NSLog(@"URL: %@", url);
-
- //第二步,创建请求
- NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
- //设置请求方式为POST,默认为GET
- [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
- [request setValue:@"Bearer 9a406a82bd551e6ef8e845f42f788af4" forHTTPHeaderField:@"Authorization"];
- [request setHTTPMethod:@"GET"];
-
- //设置参数
- //NSData *jsonBodyData = [NSJSONSerialization dataWithJSONObject:jsonBodyDict options:kNilOptions error:nil];
- //[request setHTTPBody:jsonBodyData];
-
- //新作法
- NSURLSession *sesson = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
-
- // 2.创建 NSURLSessionDataTask
- NSURLSessionDataTask *dataTask = [sesson dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
- if (error) {
- // error
- dispatch_async(dispatch_get_main_queue(), ^{
- [self showAlert: @"注意" : @"您所使用的連線加密(SSL)異常,基於安全考量不提供相關功能。請確認您的連線環境及App下載來源安全。" : 0];
- });
- }else {
- // 获得数据后,返回到主线程更新 UI
- dispatch_async(dispatch_get_main_queue(), ^{
- NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
- LockModel *LK= [[LockModel alloc] initWithString:responseString error:nil];
- if([LK.result_code isEqual:@"OK"]){
- self.nLockBtn.userInteractionEnabled = NO;
- self.nLockBtn.alpha = 0.4;
- self.Image.image = [UIImage imageNamed:@"Lock_off"];
-
- self.LockBtn.userInteractionEnabled = YES;
- self.LockBtn.alpha = 1;
- }else{
- [self showAlert:@"錯誤" :@"解鎖失敗,請稍後再試" :nil];
- }
- });
- }
- }];
- // 3.执行 Task
- [dataTask resume];
-
- /*
- //第三步,连接服务器
- NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
-
- NSString *jsonString = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
- //NSLog(@"CAR LOGIN:%@", jsonString);
-
- LockModel *LK= [[LockModel alloc] initWithString:jsonString error:nil];
- if([LK.result_code isEqual:@"OK"]){
- self.nLockBtn.userInteractionEnabled = NO;
- self.nLockBtn.alpha = 0.4;
- self.Image.image = [UIImage imageNamed:@"Lock_off"];
-
- self.LockBtn.userInteractionEnabled = YES;
- self.LockBtn.alpha = 1;
- }else{
- [self showAlert:@"錯誤" :@"解鎖失敗,請稍後再試" :nil];
- }
- */
- }
-
-
- - (NSString *) md5:(NSString *) input
- {
- const char *cStr = [input UTF8String];
- unsigned char digest[16];
- CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
-
- NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
-
- for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
- [output appendFormat:@"%02x", digest[i]];
-
- return output;
-
- }
-
- -(void)showAlert:(NSString *)title :(NSString *)text: (NSInteger *)type{
-
- UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title
- message:text
- preferredStyle:UIAlertControllerStyleAlert ];
-
- UIAlertAction *sinupAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
-
- }];
- [alertController addAction:sinupAction];
-
- [self presentViewController:alertController animated:YES completion:nil];
- }
-
- - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler//通过调用block,来告诉NSURLSession要不要收到这个证书
- {
- // Get remote certificate
- SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
- SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
-
- // Set SSL policies for domain name check
- NSMutableArray *policies = [NSMutableArray array];
- [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)challenge.protectionSpace.host)];
- SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
-
- // Evaluate server certificate
- SecTrustResultType result;
- SecTrustEvaluate(serverTrust, &result);
-
- BOOL certificateIsValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
-
- // Get local and remote cert data
- NSData *remoteCertificateData = CFBridgingRelease(SecCertificateCopyData(certificate));
-
- NSString *hash = [[self doSha256:remoteCertificateData] base64EncodedStringWithOptions:0];
-
- // The pinnning check
- if ([hash isEqualToString:@"FHloZIw4i6+30lmxrUujLieHlIDpxHySL1niMxvgmpU="] && certificateIsValid) {
- NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
- completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
- } else {
- completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, NULL);
- }
- }
-
- - (NSData *)doSha256:(NSData *)dataIn {
- NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
- CC_SHA256(dataIn.bytes, dataIn.length, macOut.mutableBytes);
- return macOut;
- }
-
- @end
|