// // UIViewController+Wallet.m // Unity-iPhone // // Created by zhl on 2022/9/1. // #import "UIViewController+Wallet.h" #import "QRCodeReaderViewController.h" #import "QRCodeReader.h" #import "QRCodeReaderDelegate.h" #include #include "WalletEvent.h" #include "JcWallet.h" #import #include "KeyChain/DataManager.h" #include "permission/LBXPermission.h" #include "permission/LBXPermissionSetting.h" #include "LBXScanNative.h" #include "LBXScanTypes.h" #include "QrCodeViewController.h" @import GoogleSignIn; static NSString * const kClientID = @"53206975661-0d6q9pqljn84n9l63gm0to1ulap9cbk4.apps.googleusercontent.com"; @interface UIViewController (Wallet) @end @implementation UIViewController (Wallet) +(void)toWallet:(NSString *)url{ UIApplication *app = [UIApplication sharedApplication]; [app openURL:[NSURL URLWithString:url]]; } -(void)showQRCode:(NSString *) content title:(NSString *) title oid:(NSString *) oid { NSLog(@"showQRCode content: %@, title: %@, oid: %@", content, title, oid); dispatch_async(dispatch_get_main_queue(), ^{ QrCodeViewController *vc = [QrCodeViewController new]; vc.content = content; vc.tipTitle = title; vc.autosave = TRUE; [self presentViewController:vc animated:YES completion:nil]; }); } -(void)loadRestoreKey:(NSString *)funid oid:(NSString *) oid{ NSLog(@"loadRestoreKey::funid: %@, oid:%@", funid, oid); } // save key to key chain -(void)saveKey:(NSString *) account key:(NSString *) key { [[DataManager sharedInstanceWith: SynLock] saveKey: account key: key]; } // load key from key chain -(NSString *)loadKey:(NSString *) account { NSLog(@"loadKey::account:%@", account); return [[DataManager sharedInstanceWith: SynLock] loadKey: account]; } -(void)scanQRCode:(NSString *)funid title:(NSString *) title{ NSLog(@"scanQRCode:: funId: %@ title: %@", funid, title); dispatch_async(dispatch_get_main_queue(), ^{ [self openLocalPhotoAlbum]; }); // std::string sfunid = std::string([funid UTF8String], [funid lengthOfBytesUsingEncoding:NSUTF8StringEncoding]); // if ([QRCodeReader supportsMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]]) { // static QRCodeReaderViewController *vc = nil; // static dispatch_once_t onceToken; // // dispatch_async(dispatch_get_main_queue(), ^{ // // if we are active again, we don't need to do this anymore // if (vc == nil) { // QRCodeReader *reader = [QRCodeReader readerWithMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]]; // vc = [QRCodeReaderViewController readerWithCancelButtonTitle:@"Cancel" codeReader:reader startScanningAtLoad:YES showSwitchCameraButton:YES showTorchButton:YES]; // vc.modalPresentationStyle = UIModalPresentationFormSheet; // } // // [vc setCompletionWithBlock:^(NSString *resultAsString) { // NSLog(@"Completion with result: %@", resultAsString); // [self dismissViewControllerAnimated:YES completion:^{ // // NSString *result; // if (resultAsString.length > 0) { // result = [NSString stringWithFormat:@"{errcode: 0, data: '%@'}", resultAsString]; // } else { // result = [NSString stringWithFormat:@"{errcode: 1, errmsg: 'cancel'}"]; // } // std::string sresult = std::string([result UTF8String], [result lengthOfBytesUsingEncoding:NSUTF8StringEncoding]); // WalletEvent::Emit(sfunid.c_str(), sresult.c_str()); // }]; // }]; // [self presentViewController:vc animated:YES completion:NULL]; // }); // } // else { // dispatch_async(dispatch_get_main_queue(), ^{ // UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Error" // message:@"The camera is need to scan QR codes" // preferredStyle:UIAlertControllerStyleAlert]; // //We add buttons to the alert controller by creating UIAlertActions: // UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Cancel" // style:UIAlertActionStyleCancel // handler: ^(UIAlertAction *action){ // NSLog(@"alert cancel pressed"); // }]; //You can use a block here to handle a press on this button // // // UIAlertAction *setting = [UIAlertAction actionWithTitle:@"Setting" // style:UIAlertActionStyleDefault // handler: ^(UIAlertAction *action){ // NSLog(@"setting pressed"); // NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString]; // if ([[UIApplication sharedApplication] canOpenURL:url]){ // [[UIApplication sharedApplication] openURL:url]; // } // }]; // [alertController addAction:actionOk]; // [alertController addAction:setting]; // [self presentViewController:alertController animated:YES completion:nil]; // }); // // std::string sresult = "{errcode: 1, errmsg: 'no camera permission'}"; // WalletEvent::Emit(sfunid.c_str(), sresult.c_str()); // } } -(void)signToGoogle:(NSString *) funid { GIDConfiguration *_configuration = [[GIDConfiguration alloc] initWithClientID:kClientID]; [GIDSignIn.sharedInstance signInWithConfiguration:_configuration presentingViewController:self completion:^(GIDGoogleUser *user, NSError *error) { if (error) { NSLog(@"Status: Authentication error: %@", error); } [self refreshUserInfo]; [self refreshTokenID: user funid:funid]; }]; } -(void) refreshTokenID:(GIDGoogleUser *)user funid:(NSString*) funid{ [user.authentication doWithFreshTokens:^(GIDAuthentication * _Nullable authentication, NSError * _Nullable error) { if (error) { return; } if (authentication == nil) { return; } NSString *idToken = authentication.idToken; // Send ID token to backend (example below). NSLog(@"idToken: %@", idToken); std::string methodName = "nativeCallBack"; NSString *paramStr = [NSString stringWithFormat:@"{\"errcode\": 0, \"data\": \"%@\"}", idToken]; std::string sfunid = std::string([funid UTF8String], [funid lengthOfBytesUsingEncoding:NSUTF8StringEncoding]); std::string sparam = std::string([paramStr UTF8String], [paramStr lengthOfBytesUsingEncoding:NSUTF8StringEncoding]); cocos2d::nativeCallBack(sfunid.c_str(), methodName.c_str(), sparam.c_str()); }]; } -(void)signWithGoogle:(NSString *)funid { [GIDSignIn.sharedInstance restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) { if (error) { // Show the app's signed-out state. [self signToGoogle: funid]; } else { // Show the app's signed-in state. [self refreshTokenID: user funid:funid]; } }]; } -(void)signOutGoogle:(NSString *)funid { [GIDSignIn.sharedInstance signOut]; } - (void)reportAuthStatus { GIDGoogleUser *googleUser = [GIDSignIn.sharedInstance currentUser]; if (googleUser.authentication) { NSLog(@"Status: Authenticated"); } else { // To authenticate, use Google Sign-In button. NSLog(@"Status: Not authenticated"); } [self refreshUserInfo]; } - (void)refreshUserInfo { if (GIDSignIn.sharedInstance.currentUser.authentication == nil) { return; } NSLog(@"email: %@", GIDSignIn.sharedInstance.currentUser.profile.email); NSLog(@"username: %@", GIDSignIn.sharedInstance.currentUser.profile.name); NSLog(@"userid: %@", GIDSignIn.sharedInstance.currentUser.userID); NSLog(@"givenName: %@", GIDSignIn.sharedInstance.currentUser.profile.givenName); NSLog(@"familyName: %@", GIDSignIn.sharedInstance.currentUser.profile.familyName); NSLog(@"hostedDomain: %@", GIDSignIn.sharedInstance.currentUser.hostedDomain); } -(void)checkOnSvr:(NSString *) idToken { // NSString *signinEndpoint = @"https://yourbackend.example.com/tokensignin"; // NSDictionary *params = @{@"idtoken": idToken}; // // NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:signinEndpoint]; // [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; // [request setHTTPMethod:@"POST"]; // [request setHTTPBody:[self httpBodyForParamsDictionary:params]]; // // NSOperationQueue *queue = [[NSOperationQueue alloc] init]; // [NSURLConnection sendAsynchronousRequest:request // queue:queue // completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { // if (error) { // NSLog(@"Error: %@", error.localizedDescription); // } else { // NSLog(@"Signed in as %@", data.bytes); // } // }]; } #pragma mark- - PhotoAlbum - (void)openLocalPhotoAlbum { __weak __typeof(self) weakSelf = self; [LBXPermission authorizeWithType:LBXPermissionType_Photos completion:^(BOOL granted, BOOL firstTime) { if (granted) { [weakSelf openLocalPhoto]; } else if (!firstTime ) { [LBXPermissionSetting showAlertToDislayPrivacySettingWithTitle:@"提示" msg:@"没有相册权限,是否前往设置" cancel:@"取消" setting:@"设置"]; } }]; } /*! * open local Photo Library */ - (void)openLocalPhoto { UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; picker.delegate = self; // crash on some mobile picker.allowsEditing = NO; [self presentViewController:picker animated:YES completion:nil]; } #pragma mark- - UIImagePickerControllerDelegate -(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { [picker dismissViewControllerAnimated:YES completion:^{ [self handPhotoDidFinishPickingMediaWithInfo:info]; }]; } - (void)handPhotoDidFinishPickingMediaWithInfo:(NSDictionary *)info { __block UIImage* image = [info objectForKey:UIImagePickerControllerEditedImage]; if (!image){ image = [info objectForKey:UIImagePickerControllerOriginalImage]; } if (@available(iOS 8.0, *)) { __weak __typeof(self) weakSelf = self; [LBXScanNative recognizeImage:image success:^(NSArray *array) { [weakSelf scanResultWithArray:array]; }]; }else{ NSLog(@"native低于ios8.0不支持识别图片"); } } - (void)scanResultWithArray:(NSArray*)array { if (!array || array.count < 1) { NSLog(@"error scan photo"); return; } for (LBXScanResult *result in array) { NSLog(@"scanResult:%@",result.strScanned); } if (!array[0].strScanned || [array[0].strScanned isEqualToString:@""] ) { NSLog(@"识别失败了"); return; } LBXScanResult *scanResult = array[0]; } @end