cdts/xdts-ios 3/TreeHole/Code/Base/PYAppService.m
2023-08-18 17:46:45 +08:00

831 lines
31 KiB
Objective-C
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// QSAppService.m
// QSport
//
// Created by ko1o on 2019/6/6.
// Copyright © 2019年 ko1o. All rights reserved.
//
#import "PYAppService.h"
#import "PYWebController.h"
//#import "LoginViewController.h"
#import <SafariServices/SafariServices.h>
#import "MTCacheManager.h"
//#import <BaiduActionSDK/BaiduActionSDK.h>
#import <Photos/PHPhotoLibrary.h>
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "MTShareServiceImp.h"
#import <TUILogin.h>
#import "ChatViewController.h"
#import "VIPViewController.h"
#import "WZLBadgeImport.h"
#import "ProfileCardViewController.h"
#import "ApplePayService.h"
#import "TZImagePickerController+MTImagePicker.h"
#import "KSPhotoBrowser.h"
NSString * _Nonnull const LoginSuccessNotification = @"LoginSuccessNotification";
NSString * _Nonnull const LogoutSuccessNotification = @"LogoutSuccessNotification";
static NSString * const kDidReportPayActionCacheKey = @"kDidReportPayActionCacheKey";
NSString * _Nonnull const BuyVIPSuccessNotification = @"BuyVIPSuccessNotification";
NSString * _Nonnull const BuyBottleSuccessNotification = @"BuyBottleSuccessNotification";
NSString * _Nonnull const BuyCoinSuccessNotification = @"BuyCoinSuccessNotification";
static AppConfig *gAppConfig;
@interface PYAppService ()
@property (nonatomic, strong) UIImage *avatarImage;
@property (nonatomic, strong) UIImageView *avatarImageView;
@property (nonatomic, strong) MTAlertView *alertView;
@end
@implementation PYAppService
+ (instancetype)sharedService
{
static dispatch_once_t onceToken;
static PYAppService *service;
dispatch_once(&onceToken, ^{
service = [PYAppService new];
// [[NSNotificationCenter defaultCenter] addObserver:service selector:@selector(onAppDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
});
return service;
}
+ (id)appDelegate
{
return [UIApplication sharedApplication].delegate;
}
+ (UINavigationController* )currentNavigationController
{
return [self currentViewController].navigationController;
}
+ (void) setTabbarSelectedItem:(int)itemIndex;
{
UINavigationController * nav = [self currentNavigationController];
if(nav.viewControllers.count >0 && [nav.viewControllers[0] isKindOfClass:[UITabBarController class]])
{
UITabBarController * tabbar = (UITabBarController *)(nav.viewControllers[0]);
if (itemIndex != tabbar.selectedIndex) {
if ([tabbar.selectedViewController isKindOfClass:[UINavigationController class]]) { //fixbug 把当前的nav先pop所有vc
[(UINavigationController *)(tabbar.selectedViewController) popToRootViewControllerAnimated:NO];
}
if(itemIndex >= 0 && itemIndex < tabbar.viewControllers.count)
{
tabbar.selectedIndex = itemIndex;
UINavigationController * tabbarNav = tabbar.selectedViewController;
if([tabbarNav isKindOfClass:[UINavigationController class]] && tabbarNav.viewControllers.count > 1)
{
[tabbarNav setViewControllers:[NSArray arrayWithObject:tabbarNav.viewControllers[0]]];
}
}
}
}
}
+ (void)showVipAlertWithPath:(NSString *)path title:(NSString *)title msg:(NSString *)message source:(NSString *)source{
if (title.length <= 0) {
title = @"需要小酒馆VIP";
}
if (message.length <= 0) {
message = @"查看VIP6+权限";
}
if (source == nil) {
source = path;
}
[MTAlertView showWithSetupBlcok:^(MTAlertViewConfig *config) {
config.title = title;
config.message = message;
config.cancelTitle = @"下次";
config.otherTitle = @"确定";
if ([path isEqualToString:@"open_clone"]) { //
config.cancelTitle = @"取消";
config.otherTitle = @"开通VIP";
} else if ([message containsString:@"缘分匹配"]) {
config.otherTitle = @"开通VIP";
} else if ([message containsString:@"发布次数"]) {
config.otherTitle = @"开通VIP";
} else if ([message containsString:@"切换分身"]) {
config.otherTitle = @"开通VIP";
}
config.otherHandler = ^(MTAlertButton *button) {
[self showVipVC:source];
};
}];
}
+ (UIViewController *)currentViewController
{
UIWindow *keywindow = nil;
NSEnumerator *frontToBackWindows = [UIApplication.sharedApplication.windows reverseObjectEnumerator];
for (UIWindow *window in frontToBackWindows) {
if (window.alpha <= 0.01) {
dispatch_async(dispatch_get_main_queue(), ^{
window.hidden = YES;
});
} else if ([window isMemberOfClass:UIWindow.class] && window.tag != MTWILL_DISMISS_TAG) {
keywindow = window;
break;
}
}
// UIWindow *keywindow = [UIApplication sharedApplication].delegate.window;
if (!keywindow) {
keywindow = [UIApplication sharedApplication].delegate.window;
}
UIViewController *resultVC = [self topViewController:keywindow.rootViewController];
while (resultVC.presentedViewController)
{
resultVC = [self topViewController:resultVC.presentedViewController];
}
return resultVC;
}
+ (int)selectedTabItemIndex {
UIWindow *keywindow = [UIApplication sharedApplication].delegate.window;
UITabBarController *tabVC = (UITabBarController *)keywindow.rootViewController;
if ([tabVC isKindOfClass:[UITabBarController class]]) {
return tabVC.selectedIndex;
}
return 0;
}
+ (UIViewController *)topViewController:(UIViewController *)vc
{
if ([vc isKindOfClass:[UINavigationController class]])
{
return [self topViewController:((UINavigationController *)vc).topViewController];
}
else if ([vc isKindOfClass:[UITabBarController class]])
{
return [self topViewController:((UITabBarController *)vc).selectedViewController];
}
else {
return vc;
}
return nil;
}
+ (UIWindow *)frontFullScreenWindow {
NSEnumerator *frontToBackWindows = [UIApplication.sharedApplication.windows reverseObjectEnumerator];
for (UIWindow *window in frontToBackWindows) {
BOOL windowOnMainScreen = window.screen == UIScreen.mainScreen;
BOOL windowIsVisible = !window.hidden && window.alpha > 0;
BOOL windowLevelSupported = (window.windowLevel >= UIWindowLevelNormal);
BOOL windowKeyWindow = window.isKeyWindow;
if(windowOnMainScreen && windowIsVisible && windowLevelSupported && windowKeyWindow) {
return window;
}
}
return nil;
}
+ (void)openWebVCWithTitle:(NSString *)title url:(NSString *)url
{
[[self currentNavigationController] pushViewController:[PYWebController webViewControllerWithUrl:url title:title] animated:YES];
}
+ (VIPViewController *)showVipVC:(NSString *)vipSource
{
VIPViewController *vc = [VIPViewController new];
vc.vipSource = vipSource;
PYNavigationViewController *nav = [[PYNavigationViewController alloc] initWithRootViewController:vc];
[[self currentViewController] presentViewController:nav animated:YES completion:nil];
return vc;
}
+ (VIPViewController *)sendVipVC:(NSString *)vipSource forUserID:(NSString *)userID
{
VIPViewController *vc = [VIPViewController new];
vc.vipSource = vipSource;
vc.userID = userID;
PYNavigationViewController *nav = [[PYNavigationViewController alloc] initWithRootViewController:vc];
UIWindow *keywindow = [UIApplication sharedApplication].delegate.window;
UIViewController *resultVC = [self topViewController:keywindow.rootViewController];
if([resultVC isKindOfClass:[VIPViewController class]]){
return vc ;
}
while (resultVC.presentedViewController){
return vc;
}
[[self currentViewController] presentViewController:nav animated:YES completion:nil];
return vc;
}
+ (void)showFastVipToBuy:(NSString *)source
{
//com.drink.hole.quarter.vip
//com.drink.hole.consecutive.month.vip
//20220517008 7天体验会员
[ApplePayService startVipPay:@"com.drink.hole.consecutive.twentyeight.month.vip" isFastBuy:YES source:source];
}
+ (void)pushViewControllerAnimated:(UIViewController *)vc
{
[[self currentNavigationController] pushViewController:vc animated:YES];
}
+ (BOOL)isPhoneVaild:(NSString *)account
{
BOOL viable = [account hasPrefix:@"1"] && account.length == 11;
if (!viable) {
[SVProgressHUD showInfoWithStatus:@"请输入正确的手机号"];
}
return viable;
}
+ (void)login
{
[SVProgressHUD showWithStatus:nil];
[UserService getUserInfoWithCompletion:^(User * _Nonnull user) {
if (user) {
// 登录成功 登录IM
[TUILogin login:TIM_APPID userID:[UserService currentUser].im_user_id userSig:[LoginService userSig] succ:^{
NSLog(@"-----> 登录成功%@",[UserService currentUser].im_user_id);
[SVProgressHUD dismiss];
[[NSNotificationCenter defaultCenter] postNotificationName:LoginSuccessNotification object:nil];
//绑定idfa到用户
[PYHTTPManager postWithPath:@"bindingdevice" params:@{@"idfa": [UserService idfa]} callback:^(id _Nullable rsp, NSError * _Nullable error) {
if (!error) {
}
}];
} fail:^(int code, NSString *msg) {
[SVProgressHUD showErrorWithStatus:@"IM登录失败"];
[PYAppService logout];
}];
}
}];
}
+ (void)logout
{
[TUILogin logout:^{
[SVProgressHUD dismiss];
[LoginService clearToken];
[UserService clearUser];
[[NSNotificationCenter defaultCenter] postNotificationName:LogoutSuccessNotification object:nil];
} fail:^(int code, NSString *msg) {
[SVProgressHUD showErrorWithStatus:msg ?: @"IM登出失败"];
}];
}
+ (void)showLoginVC
{
// if ([[self currentViewController] isKindOfClass:[LoginViewController class]]) {
// return;
// }
// LoginViewController *loginVC = [LoginViewController sharedInstance];
//
// PYNavigationViewController *nav = [[PYNavigationViewController alloc] initWithRootViewController:loginVC];
// [[self currentNavigationController] presentViewController:nav animated:YES completion:nil];
}
+ (BOOL)showLoginVCIfNeed
{
if ([UserService isLogined]) {
return NO;
}
[self showLoginVC];
return YES;
}
+ (BOOL)showBuyVipVCIfNeed
{
if ([self showLoginVCIfNeed]) {
return YES;
}
// if ([UserService currentUser].isVip || [AppConifgService isReviewVersion]) {
// return NO;
// }
//
// NSString *cacheUseCountKey = @"cacheUseCountKey";
//
// NSInteger useCount = [[MTCacheManager userPersistanceManager] integerForKey:cacheUseCountKey];
// int limtUseCount = [AppConifgService currentConfig].sys.guest_use_num ?: 1;
// if (useCount >= limtUseCount) {
// [MTAlertView showWithSetupBlcok:^(MTAlertViewConfig *config) {
// config.title = @"您的免费次数已用完\n购买会员后可无限保存";
// config.otherTitle = @"立即开通";
// config.cancelTitle = @"关闭";
// config.otherHandler = ^(MTAlertButton *button) {
// [self pushViewControllerAnimated:[[VipViewController alloc] init]];
// };
// }];
// return YES;
// } else {
// useCount ++;
// [[MTCacheManager userPersistanceManager] setInteger:useCount forKey:cacheUseCountKey];
// }
//
return NO;
}
+ (void)openSafariVCWithTitle:(NSString *)title url:(NSString *)url
{
SFSafariViewControllerConfiguration *config = [[SFSafariViewControllerConfiguration alloc] init];
SFSafariViewController *safariVC = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:url?:@""] configuration:config];
safariVC.title = title;
[[self currentViewController] presentViewController:safariVC animated:YES completion:nil];
// [[self currentNavigationController] pushViewController:safariVC animated:nil];
}
+ (void)jumpToSystemAppSettingsPage {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
+ (BOOL)showAuthorizationWithTypeIfNeed:(AuthorizationType)type
{
void(^showAlert)(NSString *title, NSString *message) = ^(NSString *title, NSString *message) {
[MTAlertView showWithSetupBlcok:^(MTAlertViewConfig *config) {
config.title = title;
config.message = message;
config.cancelTitle = @"取消";
config.otherTitle = @"去授权";
config.otherHandler = ^(MTAlertButton *button) {
[self jumpToSystemAppSettingsPage];
};
}];
};
switch (type) {
case AuthorizationTypePhoto:
{
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
showAlert(@"无相册访问权限", @"请前往设置页进行授权");
return YES;
} else if (status == PHAuthorizationStatusNotDetermined) {
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
__block bool isAllow = NO;
if (@available(iOS 14, *)) {
[PHPhotoLibrary requestAuthorizationForAccessLevel:PHAccessLevelReadWrite handler:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusAuthorized) {
isAllow = YES;
} else{
isAllow = NO; //回到主线程
}
dispatch_semaphore_signal(semaphore);
}];
} else {
// Fallback on earlier versions
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusAuthorized) {
isAllow = YES;
} else{
isAllow = NO; //回到主线程
}
dispatch_semaphore_signal(semaphore);
}];
}
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
if (!isAllow) {
showAlert(@"无相册访问权限", @"请前往设置页进行授权");
}
return !isAllow;
}
break;
}
case AuthorizationTypeCapture: { // 相机
AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied)
{
showAlert(@"无相机访问权限", @"请前往设置页进行授权");
return YES;
} else if (status == AVAuthorizationStatusNotDetermined) {
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
__block bool isAllow = NO;
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
isAllow = granted;
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
if (!isAllow) {
showAlert(@"无相机访问权限", @"请前往设置页进行授权");
}
return !isAllow;
}
break;
}
case AuthorizationTypeMicrophone: {
AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied)
{
showAlert(@"无麦克风访问权限", @"请前往设置页进行授权");
return YES;
} else if (status == AVAuthorizationStatusNotDetermined) {
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
__block bool isAllow = NO;
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
isAllow = granted;
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
if (!isAllow) {
showAlert(@"无麦克风访问权限", @"请前往设置页进行授权");
}
return !isAllow;
}
break;
}
case AuthorizationTypeLocation: {
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
showAlert(@"无位置访问权限", @"请前往设置页进行授权");
return YES;
}
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) {
return NO;
}
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
PYAppService *appService = [PYAppService sharedService];
CLLocationManager *cLLocationManager = [[CLLocationManager alloc] init];
[cLLocationManager requestAlwaysAuthorization];
[cLLocationManager requestWhenInUseAuthorization];
appService.cLLocationManager = cLLocationManager;
return NO;
}
return NO;
break;
}
default:
break;
}
return NO;
}
+ (void)chatWithUser:(User *)user {
if (user.im_user_id.length <= 0) {
return;
}
ChatViewController *chatVC = [[ChatViewController alloc] init];
TUIConversationCellData *data = [[TUIConversationCellData alloc] init];
data.userID = user.im_user_id;
data.title = user.nickname;
data.faceUrl = user.avatar;
data.conversationID = [@"c2c_" stringByAppendingString:data.userID];
chatVC.convData = data;
[PYAppService pushViewControllerAnimated:chatVC];
}
+ (BOOL)handleUrl:(NSString *)url {
if (url.length <= 0) {
return NO;
}
if (([url hasPrefix:@"hole://"] || [url hasPrefix:UNIVERSAL_LINK]) && [UserService isLogined]) {
NSString *queryStr = [[NSURL URLWithString:url] query];
NSDictionary *params = [self parseQueryComponentsFromQueryString:queryStr];
int type = [params[@"type"] intValue];
return YES;
}
if ([url hasPrefix:@"http"]) {
[PYAppService openWebVCWithTitle:@"" url:url];
return YES;
}
return NO;
}
+ (NSMutableDictionary *)parseQueryComponentsFromQueryString:(NSString *)queryStr {
NSMutableDictionary *results = [NSMutableDictionary dictionary];
if (queryStr && queryStr.length) {
NSString *queryCopy = [queryStr copy];
NSArray *components = [queryCopy componentsSeparatedByString:@"&"];
for (NSString *component in components) {
NSRange range = [component rangeOfString:@"="];
NSString *key, *value;
if (range.location == NSNotFound) {
key = component;
value = @"";
} else {
key = [component substringToIndex:range.location];
value = [component substringFromIndex:range.location + 1];
}
if (value == nil)
value = @"";
//必须至少有个keyvalue默认为空字符串
if (key && key.length && value) {
[results setObject:value forKey:key];
}
}
}
return results;
}
+ (AppConfig *)appConfig {
if (!gAppConfig) {
[PYHTTPManager getWithPath:@"configs" params:nil callback:^(id _Nullable rsp, NSError * _Nullable error) {
if (!error) {
gAppConfig = [AppConfig mj_objectWithKeyValues:rsp];
}
}];
}
return gAppConfig;
}
+ (void)getAppConfigWithCompletion:(void(^)(AppConfig *config))completion {
if (!gAppConfig) {
[PYHTTPManager getWithPath:@"configs" params:nil callback:^(id _Nullable rsp, NSError * _Nullable error) {
if (!completion) {
return;
}
if (!error) {
gAppConfig = [AppConfig mj_objectWithKeyValues:rsp];
completion(gAppConfig);
} else {
completion(nil);
}
}];
}
if (completion) {
completion(gAppConfig);
}
}
+ (void)buyTryVIP {
// [PYHTTPManager postWithPath:@"wxgoodprepay" params:@{
// @"vip_good_id": @(4) // 体验会员
// } callback:^(id _Nullable rsp, NSError * _Nullable error) {
// if (error) {
// [SVProgressHUD showErrorWithStatus:error.localizedDescription];
// return;
// }
// [PYAppService payByWetChatPayWithOrderId:rsp[@"trade_no"] payInfo:rsp];
// }];
}
+ (BOOL)showUploadAvatarAlertIfNeed {
if (![UserService currentUser].is_default_avatar) {
return NO;
}
UIView *setupCloneInfoView = [[UIView alloc] init];
setupCloneInfoView.width = kMTAlertContentSizeDefaultWidth;
UILabel *avatarTitleLabel = [[UILabel alloc] init];
avatarTitleLabel.font = MT_FONT_MEDIUM_SIZE(16);
avatarTitleLabel.text = @"请先设置下你漂亮的头像";
avatarTitleLabel.textColor = [UIColor whiteColor];
avatarTitleLabel.y = FIX_SIZE(30);
[avatarTitleLabel sizeToFit];
avatarTitleLabel.centerX = setupCloneInfoView.width * 0.5;
[setupCloneInfoView addSubview:avatarTitleLabel];
UIView *addAvatarItem = [[UIView alloc] init];
addAvatarItem.size = CGSizeMake(FIX_SIZE(120), FIX_SIZE(120));
addAvatarItem.backgroundColor = SUB_BG_COLOR;
addAvatarItem.layer.cornerRadius = FIX_SIZE(16);
addAvatarItem.clipsToBounds = YES;
addAvatarItem.y = avatarTitleLabel.bottom + FIX_SIZE(15);
addAvatarItem.centerX = setupCloneInfoView.width * 0.5;
[addAvatarItem addTapWithAction:^{
TZImagePickerController *picker = [TZImagePickerController mt_imagePickerWithMaxImagesCount:1 didFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
if (photos.count) {
[PYAppService sharedService].avatarImageView.image = photos.firstObject;
[PYAppService sharedService].avatarImageView.hidden = NO;
[PYAppService sharedService].avatarImage = [PYAppService sharedService].avatarImageView.image;
}
}];
[[PYAppService currentNavigationController] presentViewController:picker animated:YES completion:nil];
}];
[setupCloneInfoView addSubview:addAvatarItem];
UIImageView *addIconView = [[UIImageView alloc] init];
addIconView.size = CGSizeMake(FIX_SIZE(26), FIX_SIZE(26));
addIconView.image = [ImageNamed(@"TH_login_add_icon") mt_imageWithTintColor:UIColor.whiteColor];
addIconView.center = CGPointMake(addAvatarItem.width * 0.5, addAvatarItem.height * 0.5);
[addAvatarItem addSubview:addIconView];
UILabel *addLabel = [[UILabel alloc] init];
addLabel.text = @"点击选取头像";
addLabel.textColor = CONTENT_COLOR;
addLabel.font = SMALL_FONT;
[addLabel sizeToFit];
addLabel.y = addIconView.bottom + FIX_SIZE(13.5);
addLabel.centerX = addIconView.centerX;
[addAvatarItem addSubview:addLabel];
PYImageView *avatarImageView = [[PYImageView alloc] init];
avatarImageView.frame = addAvatarItem.bounds;;
avatarImageView.backgroundColor = addAvatarItem.backgroundColor;
avatarImageView.hidden = YES;
[addAvatarItem addSubview:avatarImageView];
[PYAppService sharedService].avatarImageView = avatarImageView;
[PYAppService sharedService].avatarImage = nil;
setupCloneInfoView.height = addAvatarItem.bottom;
// setupCloneInfoView.height = 100;
[PYAppService sharedService].alertView = [MTAlertView showWithSetupBlcok:^(MTAlertViewConfig *config) {
config.customView = setupCloneInfoView;
config.cancelTitle = @"下次";
config.otherTitle = @"OK";
config.otherHandler = ^(MTAlertButton *button) {
if (![PYAppService sharedService].avatarImage) {
[ToastUtil showToast:@"请先选择头像"];
button.tag = MTNO_DISMISS_TAG;
return;
}
button.tag = MTNO_DISMISS_TAG;
[SVProgressHUD showWithStatus:nil];
[PYHTTPManager uploadFileWithScene:AliOSSUploadSceneAvatar data:compressImageToDataIfNeed([PYAppService sharedService].avatarImage) completion:^(id _Nullable rsp, NSError * _Nullable error) {
if (!error) {
[UserService updateUserToRemoteWithParams:@{
@"avatar": rsp ?: @"",
} completion:^(id _Nullable rsp, NSError * _Nullable error) {
if (!error) { // 上传完成
[UserService currentUser].is_default_avatar = false;
[[PYAppService sharedService].alertView dismiss];
} else {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[SVProgressHUD showErrorWithStatus:[error.userInfo objectForKey:@"message"]];
});
}
}];
}
}];
};
}];
return YES;
}
static NSString *currentOrderId = nil;
static NSString *currentUserId = nil;
+ (void)payByWetChatPayWithOrderId:(NSString *)orderId payInfo:(NSDictionary *)payInfo
{
currentOrderId = orderId;
currentUserId = @"";
PayReq *request = [[PayReq alloc] init];
request.partnerId = payInfo[@"partnerId"];
request.prepayId= payInfo[@"prepayId"];
request.package = payInfo[@"package"];
request.nonceStr= payInfo[@"nonceStr"];
request.timeStamp= [payInfo[@"timeStamp"] intValue];
request.sign = payInfo[@"sign"];
[WXApi sendReq:request completion:^(BOOL success) {
if (!success) {
[SVProgressHUD showErrorWithStatus:@"唤起微信支付失败"];
}
}];
}
+ (void)payByWetChatPayWithOrderId:(NSString *)orderId payInfo:(NSDictionary *)payInfo userId:(NSString *)userId {
currentUserId = userId;
currentOrderId = orderId;
PayReq *request = [[PayReq alloc] init];
request.partnerId = payInfo[@"partnerId"];
request.prepayId= payInfo[@"prepayId"];
request.package = payInfo[@"package"];
request.nonceStr= payInfo[@"nonceStr"];
request.timeStamp= [payInfo[@"timeStamp"] intValue];
request.sign = payInfo[@"sign"];
[WXApi sendReq:request completion:^(BOOL success) {
if (!success) {
[SVProgressHUD showErrorWithStatus:@"唤起微信支付失败"];
}
}];
}
- (void)onAppDidBecomeActive {
// [self checkWXOrderIFNeed];
}
- (void)checkWXOrderIFNeed {
if (!currentOrderId) {
return;
}
[PYHTTPManager postWithPath:@"wxcheckorder" params:@{
@"order_uuid": currentOrderId ?: @""
} callback:^(id _Nullable rsp, NSError * _Nullable error) {
if (!error) {
[SVProgressHUD dismiss];
if ([rsp[@"is_pay_succeed"] boolValue]) {
if (currentUserId.length > 0) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"receivedVipMsgnotifi" object:currentUserId];
currentOrderId = nil;
currentUserId = nil;
} else {
[[NSNotificationCenter defaultCenter] postNotificationName:BuyVIPSuccessNotification object:nil];
[MTAlertView showWithSetupBlcok:^(MTAlertViewConfig *config) {
config.title = @"VIP购买成功";
config.message = @"你现在是我们小酒馆最尊贵的客人";
config.otherTitle = @"确定";
}];
}
} else {
// [SVProgressHUD showErrorWithStatus:@"支付失败"];
}
} else {
[SVProgressHUD showErrorWithStatus:@"支付失败"];
}
}];
}
+ (void)showBadgeOnTabBarItemAtIndex:(int)index number:(int)number {
UIWindow *keywindow = [UIApplication sharedApplication].delegate.window;
UITabBarController *tabVC = (UITabBarController *)keywindow.rootViewController;
if (![tabVC isKindOfClass:[UITabBarController class]]) {
return;
}
int unreadCount = number;
NSArray *subviews = [[tabVC tabBar] subviews];
UIView *tabBarButton = nil;
NSMutableArray *tabBarButtons = [NSMutableArray array];
for (UIView *subview in subviews) {
if ([subview isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
[tabBarButtons addObject:subview];
}
}
[tabBarButtons sortUsingComparator:^NSComparisonResult(UIView *obj1, UIView *obj2) {
return obj1.x > obj2.x;
}];
if (index >= tabBarButtons.count) {
return;
}
tabBarButton = tabBarButtons[index];
UIView *iconView;
for (UIView *subview in tabBarButton.subviews) {
if ([subview isKindOfClass:UIImageView.class]) {
iconView = subview;
break;
}
}
iconView.badgeCenterOffset = CGPointMake(-5, 5);
if (unreadCount > 0) {
[iconView showBadgeWithStyle:WBadgeStyleNumber value:unreadCount animationType:WBadgeAnimTypeNone];
} else if (unreadCount == -1) {
[iconView showBadgeWithStyle:WBadgeStyleRedDot value:unreadCount animationType:WBadgeAnimTypeNone];
} else {
[iconView clearBadge];
}
}
+ (void)showUserCardVCWithUserID:(int)userID {
[self pushViewControllerAnimated:[[ProfileCardViewController alloc] initWithUserID:userID]];
}
/// 图片查看大图
+ (KSPhotoBrowser *)showImageBrowserWithImageURLs:(NSArray<NSString *> *)imageURLs index:(NSInteger)index {
NSMutableArray *items = @[].mutableCopy;
for (int i = 0; i < imageURLs.count; i++) {
KSPhotoItem *item = [KSPhotoItem itemWithSourceView:nil imageUrl:[NSURL URLWithString:imageURLs[i]]];
[items addObject:item];
}
KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:items selectedIndex:index];
browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleText;
browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlack;
[KSPhotoBrowser setImageViewBackgroundColor:[UIColor clearColor]];
browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleScale;
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:browser];
nav.modalPresentationStyle = UIModalPresentationOverFullScreen;
[[PYAppService currentNavigationController] presentViewController:nav animated:NO completion:nil];
return browser;
}
#pragma mark - WXApiDelegate
/// 微信回调
- (void)onResp:(BaseResp *)resp
{
if ([resp isKindOfClass:[PayResp class]]) { // 支付回调
[self checkWXOrderIFNeed];
}
}
@end