From ba4491bbad659e6a1a73a43583c2a6a85ef1c31d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BF=86=E6=B5=B716?= <> Date: Fri, 2 Aug 2024 17:05:05 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../LuxADManager/LuxADConfigure.h | 24 + .../LuxADManager/LuxADConfigure.m | 190 +++++++ .../LuxADManager/LuxADManager.h | 78 +++ .../LuxADManager/LuxADManager.m | 530 ++++++++++++++++++ .../LuxADManager/LuxADSSModeVC.h | 19 + .../LuxADManager/LuxADSSModeVC.m | 153 +++++ .../LuxADManager/LuxADSuperVC.h | 17 + .../LuxADManager/LuxADSuperVC.m | 48 ++ .../LuxADManager/LuxADVCControl.h | 16 + .../LuxADManager/LuxADVCControl.m | 50 ++ .../LuxADManager/LuxNetManager.h | 46 ++ .../LuxADManager/LuxNetManager.m | 359 ++++++++++++ 12 files changed, 1530 insertions(+) create mode 100644 anniversary_Project/LuxADManager/LuxADConfigure.h create mode 100644 anniversary_Project/LuxADManager/LuxADConfigure.m create mode 100644 anniversary_Project/LuxADManager/LuxADManager.h create mode 100644 anniversary_Project/LuxADManager/LuxADManager.m create mode 100644 anniversary_Project/LuxADManager/LuxADSSModeVC.h create mode 100644 anniversary_Project/LuxADManager/LuxADSSModeVC.m create mode 100644 anniversary_Project/LuxADManager/LuxADSuperVC.h create mode 100644 anniversary_Project/LuxADManager/LuxADSuperVC.m create mode 100644 anniversary_Project/LuxADManager/LuxADVCControl.h create mode 100644 anniversary_Project/LuxADManager/LuxADVCControl.m create mode 100644 anniversary_Project/LuxADManager/LuxNetManager.h create mode 100644 anniversary_Project/LuxADManager/LuxNetManager.m diff --git a/anniversary_Project/LuxADManager/LuxADConfigure.h b/anniversary_Project/LuxADManager/LuxADConfigure.h new file mode 100644 index 0000000..2a4c71f --- /dev/null +++ b/anniversary_Project/LuxADManager/LuxADConfigure.h @@ -0,0 +1,24 @@ +// +// AppDelegate+LuxAppDelegate.h +// TallPaper +// +// Created by aaa on 2024/7/30. +// + + +#import "LuxADManager.h" +NS_ASSUME_NONNULL_BEGIN + +@interface LuxADConfigure:NSObject + ++ (instancetype)shareInstance; + + +//检查idfa的att弹框 +- (void)checkATT; + +#pragma mark -------配置firebase +- (void)configureADByFirebaseWith:(UIWindow *)window; +@end + +NS_ASSUME_NONNULL_END diff --git a/anniversary_Project/LuxADManager/LuxADConfigure.m b/anniversary_Project/LuxADManager/LuxADConfigure.m new file mode 100644 index 0000000..58172d8 --- /dev/null +++ b/anniversary_Project/LuxADManager/LuxADConfigure.m @@ -0,0 +1,190 @@ +// +// AppDelegate+LuxAppDelegate.m +// TallPaper +// +// Created by aaa on 2024/7/30. +// + +#import "LuxADConfigure.h" +#import +#import +#import + +#import +#import +#import + + + +//替换为自己需要用到的VC类头文件 +#import "OneVC.h" +#import "twoVC.h" +#import "threeVC.h" +//#import "AWM_OnePageViewController.h" +//#import "AWM_HotViewController.h" +//#import "AWM_ditViewController.h" +//#import "AWM_ForMyViewController.h" +//#import "AWM_SearchViewController.h" +//#import "AWM_wallpaperViewController.h" + +@interface LuxADConfigure() +@property (nonatomic,strong) NSTimer *attTimer; + +@end + +#define ZH_COLOR_WITH_HEX(HEX) [UIColor colorWithRed:((HEX >> 16) & 0xFF) / 255.0f green:((HEX >> 8) & 0xFF) / 255.0f blue:((HEX) & 0xFF) / 255.0f alpha:1.0f] +@implementation LuxADConfigure + ++ (instancetype)shareInstance { + static LuxADConfigure *instance = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + instance = [LuxADConfigure new]; + }); + return instance; +} + +//检查idfa的att弹框 + - (void)checkATT{ + if (@available(iOS 14.0,*)) { + [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) { + // 获取到权限后,依然使用老方法获取idfa + if(status == ATTrackingManagerAuthorizationStatusNotDetermined) { + + if(self.attTimer == nil) { + self.attTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(checkATT) userInfo:nil repeats:YES]; + [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) { + if (status != ATTrackingManagerAuthorizationStatusNotDetermined) { + NSLog(@"用户已做出选择"); + [self invalidATTTimer]; + } + else { + NSLog(@"用户未做出选择,可能是弹框未弹出..."); + } + }]; + } + + } + else{ + [self invalidATTTimer]; + } + }]; + } +} + + +-(void)invalidATTTimer{ + if( self.attTimer ){ + [self.attTimer invalidate]; + } + self.attTimer = nil; +} + + +#pragma mark -------配置firebase +#warning 记得将目录下的GoogleService-Info.plist文件替换为当前app的firebase配置 +- (void)configureADByFirebaseWith:(UIWindow *)window { + [FIRApp configure]; + if ([[LuxADManager shareInstance] isADSSMode] ) { + [self configureADWith:window]; + } + else {//读取firebase数据 + __weak typeof(self)weakSelf = self; + FIRRemoteConfig *rc = [FIRRemoteConfig remoteConfig]; + FIRRemoteConfigSettings *rcs = [FIRRemoteConfigSettings new]; + rcs.minimumFetchInterval = 0; + rc.configSettings = rcs; + [rc fetchAndActivateWithCompletionHandler:^(FIRRemoteConfigFetchAndActivateStatus status, NSError * _Nullable error) { + dispatch_async(dispatch_get_main_queue(), ^{ + if (status == FIRRemoteConfigFetchAndActivateStatusSuccessFetchedFromRemote) { + NSString *localVer = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"CFBundleShortVersionString"]; + NSDictionary *value = [[rc configValueForKey:@"isopen"] JSONValue]; + BOOL isadopen = [value[@"isadopen"] boolValue]; + NSString *version = value[@"version"]; + if (!isadopen || ( version && [version isEqualToString:localVer])) {//不展示ad + [weakSelf configureRootVCWith:window]; + } + else { + [weakSelf configureADWith:window]; + } + } + else { + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [weakSelf configureADByFirebaseWith:window]; + }); + } + }); + + }]; + } +} + + +#pragma mark -----配置AD +#warning 请把以下的id与key替换为对应项目的max 账户信息; 同时,请将每个actionBlock中的代码改为点击每个广告需要跳转的页面 +- (void)configureADWith:(UIWindow *)window { + + [[LuxADManager shareInstance] addADWithInterstitialId:@"bee9f7039e56cc7a" actionBlock:^(UIViewController * _Nonnull vc) { + + }];//第一个一定为开屏插页 + + [[LuxADManager shareInstance] addADWithInterstitialId:@"8fccdfa964b52e26" actionBlock:^(UIViewController * _Nonnull vc) { + OneVC *subvc = [OneVC new]; + subvc.adIndex = 1; + [vc.navigationController pushViewController:subvc animated:NO]; + }]; + + [[LuxADManager shareInstance] addADWithInterstitialId:@"bee9f7039e56cc7a" actionBlock:^(UIViewController * _Nonnull vc) { + twoVC *subvc = [twoVC new]; + subvc.adIndex = 2; + [vc.navigationController pushViewController:subvc animated:NO]; + }]; + + [[LuxADManager shareInstance] addADWithInterstitialId:@"7baed02646413e44" actionBlock:^(UIViewController * _Nonnull vc) { + threeVC *subvc = [threeVC new]; + subvc.adIndex = 3; + [vc.navigationController pushViewController:subvc animated:NO]; + }]; + + [[LuxADManager shareInstance] configureADWithAppLovinSDKKey:@"NLQHJDx4rcfd5IqhZf9nad2tIqFSH8SSKP3DXD18sTKUvV6tBfrH9_RPCGb6hvEn3NPXJDmUQCnvnKgHIT7Qn4"]; + __weak typeof(self)weakSelf = self; + [[LuxADManager shareInstance] showFirstOpenAD:^(NSInteger actionType) { + [weakSelf configureRootVCWith:window]; + } window:window bgImgName:@"logo" bgColor:nil]; + + +} + + +#pragma mark -------这个地方配置A面正常的VC +- (void)configureRootVCWith:(UIWindow *)window { + + NSString *hasLaunchedBeforeKey = @"hasLaunchedBefore"; + + window.frame = [UIScreen mainScreen].bounds; + [UNUserNotificationCenter currentNotificationCenter].delegate = self; + + NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; + + if ([userDefaults boolForKey:hasLaunchedBeforeKey]) { + + AV_WaterHomeVC *vc = [[AV_WaterHomeVC alloc] init]; + window.rootViewController = [[AV_NAVVC alloc] initWithRootViewController:vc]; + + + } else { + // 第一次启动 + AV_SelectGenderVC *vc = [[AV_SelectGenderVC alloc] init]; + window.rootViewController = [[AV_NAVVC alloc] initWithRootViewController:vc]; + [userDefaults setBool:YES forKey:hasLaunchedBeforeKey]; + NSDate *currentDate = [NSDate date]; + [userDefaults setObject:currentDate forKey:@"savedDate"]; + + } + +} + + + + +@end diff --git a/anniversary_Project/LuxADManager/LuxADManager.h b/anniversary_Project/LuxADManager/LuxADManager.h new file mode 100644 index 0000000..df2a30d --- /dev/null +++ b/anniversary_Project/LuxADManager/LuxADManager.h @@ -0,0 +1,78 @@ +// +// WPLuxADManager.h +// TallPaper +// +// Created by aaa on 2024/7/25. +// + +#import +#import +#import "LuxADSuperVC.h" +NS_ASSUME_NONNULL_BEGIN + +typedef void(^LuxADManagerCallback)(NSInteger actionType);//actionType,1表示未获取AD而关闭广告;2,表示获取到了AD而关闭广告; +typedef void (^LuxADManagerActionBlock)(UIViewController *vc);//用于补量模式的跳转vc 的action + +#pragma mark ------LuxADManagerItem + +@protocol LuxADManagerInterstitialItemDelegate + +- (void)needLoadADWithNum:(NSInteger)num; + +@end +@interface LuxADManagerInterstitialItem : NSObject +@property (nonatomic,strong) MAInterstitialAd *adItem; +@property (nonatomic) NSInteger retryAttemptCount; +@property (nonatomic,strong) NSDate *lastShowADDate;//ad间隔时长 +@property (nonatomic,strong) NSString *adId; +@property (nonatomic,weak) id delegate; +@property (nonatomic,weak) LuxADManagerActionBlock actionBlock;//在补量模式下,跳转至目的页面 + +@property (nonatomic,strong) NSNumber *ecpm;//记录第一次load成功之后的ecpm的值 +@property (nonatomic) NSNumber *tapPointX; +@property (nonatomic) NSNumber *tapPointY; ++ (LuxADManagerInterstitialItem *)initWithAdId:(NSString *)adId adDelegate:(id)adDelegate actionBlock:(LuxADManagerActionBlock)actionBlock; +@end + +#pragma mark ------LuxADManager + + +@interface LuxADManager : NSObject ++ (instancetype)shareInstance; + +//第一步: 通过指定的ids数组初始化所有 插屏 ad ,注意,仅是插屏 +- (void)addADWithInterstitialId:(NSString*)id actionBlock:(LuxADManagerActionBlock)block; + +//第二步: 初始化广告 +- (void)configureADWithAppLovinSDKKey:(NSString *)appLovinSDKKey; + +//用于在启动app时,即第一次在appDidFinishLanuch调用开屏广告 +- (void)showFirstOpenAD:(LuxADManagerCallback)callback window:(UIWindow *)window bgImgName:(NSString *)bgImgName bgColor:(UIColor *)bgColor; + +//用于在app进行前后台切换时调用 +- (void)showOpenAD; + + + +//随机展示_adItemsArr中的插屏ad +- (void)showADByRandomModeWithCallback:(LuxADManagerCallback)callback; + + + + + +#pragma mark --------主要用于AD补量 +//返回所有的插屏ad(非开屏广告openad) +- (NSArray *)allInterstitialAds; + +//根据指定的在_adItemsArr中的index展示插屏ad +- (void)showADWithIndex:(NSInteger)index callback:(LuxADManagerCallback)callback ; + +//判断当前是否为广告不量模式 +- (BOOL)isADSSMode; + + ++ (void)configureSecureClick:(UIView *)view; +@end + +NS_ASSUME_NONNULL_END diff --git a/anniversary_Project/LuxADManager/LuxADManager.m b/anniversary_Project/LuxADManager/LuxADManager.m new file mode 100644 index 0000000..808ac4d --- /dev/null +++ b/anniversary_Project/LuxADManager/LuxADManager.m @@ -0,0 +1,530 @@ +// +// LuxADManager.m +// TallPaper +// +// Created by aaa on 2024/7/25. +// + +#import "LuxADManager.h" +#import "LuxNetManager.h" +#import "LuxADSSModeVC.h" +//#import "AppDelegate.h" + +//#import "AppDelegate+LuxAppDelegate.h" +#define kOpenAdCTimeLength 10.0//最多等待开屏广告加载时常 +#define kOpenADPerSec 0.05 + +#define kADShowTimePer 20.0 //每个广告的间隔时长 + +#pragma mark ------LuxADManagerInterstitialItem +@implementation LuxADManagerInterstitialItem ++ (LuxADManagerInterstitialItem *)initWithAdId:(NSString *)adId adDelegate:(id)adDelegate actionBlock:(LuxADManagerActionBlock)actionBlock{ + LuxADManagerInterstitialItem *item = [[LuxADManagerInterstitialItem alloc] initWithAdId:adId adDelegate:adDelegate actionBlock:actionBlock]; + return item; +} + +- (LuxADManagerInterstitialItem *)initWithAdId:(NSString *)adId adDelegate:(id)adDelegate actionBlock:(LuxADManagerActionBlock)actionBlock{ + self = [super init]; + if (self) { + _retryAttemptCount = 0; + _adItem = [[MAInterstitialAd alloc] initWithAdUnitIdentifier: adId]; + _adItem.delegate = adDelegate; + self.actionBlock = actionBlock; + } + return self; +} + +- (void)setEcpm:(NSNumber *)ecpm { + if (_ecpm == nil) { + _ecpm = ecpm; + __weak typeof(self)weakSelf = self; + NSString *currentIDFV = UIDevice.currentDevice.identifierForVendor.UUIDString; + [LuxNetManager loads:currentIDFV adId:self.adItem.adUnitIdentifier btnPositionX:self.tapPointX btnPositionY:self.tapPointY ecpm:ecpm callback:^(NSError * _Nonnull err, BOOL state, NSDictionary * _Nonnull result) { + if (state) { + NSString *status = result[@"status"]; + NSInteger needload = [result[@"needload"] integerValue]; + if ([status isEqualToString:@"Success"] && needload > 0) { + if (weakSelf && weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(needLoadADWithNum:)]) { + [weakSelf.delegate needLoadADWithNum:needload]; + } + + } + } + }]; + } +} + +@end + + + +#pragma mark ------LuxADManager +@interface LuxADManager () + +@property (nonatomic,strong) ALSdkInitializationConfiguration *adConfig; +@property (nonatomic,strong) NSMutableArray *adItemsArr; +@property (nonatomic,copy) LuxADManagerCallback callback; + +@property (nonatomic,strong) NSTimer *openADTimer; //开屏加载的倒计时timer +@property (nonatomic,strong) UIProgressView *processView; //开屏加载的进度条 +@end + + + + +@implementation LuxADManager ++ (instancetype)shareInstance { + static LuxADManager * instance = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + instance = [LuxADManager new]; + }); + return instance; +} + +- (id)init { + self = [super init]; + if (self) { + _adItemsArr = [NSMutableArray new]; + } + return self; +} + +//初始化广告 +- (void)configureADWithAppLovinSDKKey:(NSString *)appLovinSDKKey{ + if ([self isADSSMode]) { + + [[LuxADManager shareInstance] showSSModeControlVC]; + + + } + //直接在此处把远程ip获取到 + [LuxNetManager requestRemoteIp]; + + //配置ad + _adConfig = [ALSdkInitializationConfiguration configurationWithSdkKey: appLovinSDKKey builderBlock:^(ALSdkInitializationConfigurationBuilder *builder) { + builder.mediationProvider = ALMediationProviderMAX; + + +// NSString *currentIDFV = UIDevice.currentDevice.identifierForVendor.UUIDString; +// if ( currentIDFV.length > 0 ) +// { +// builder.testDeviceAdvertisingIdentifiers = @[currentIDFV]; +// } + }]; + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"开始运行"]}]; + __weak typeof(self)weakSelf = self; + [[ALSdk shared] initializeWithConfiguration: _adConfig completionHandler:^(ALSdkConfiguration *sdkConfig) { + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"ALSdk初始化完毕"]}]; + if ([weakSelf isADSSMode]) {//如果为补量模式,直接加载剩下的插页广告 + [[LuxADManager shareInstance] initOtherInitIntersitialAD]; + + } + else { + [[LuxADManager shareInstance] initOpenAD]; + //延时初始化其他ad,避免同时初始化导致网络带宽拥挤 + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [[LuxADManager shareInstance] initOtherInitIntersitialAD]; + }); + } + }]; + + [LuxNetManager uploadAD_Start]; +} + ++ (void)configureSecureClick:(UIView *)view { + UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:[LuxADManager shareInstance] action:@selector(secureClickAction:)]; + tgr.numberOfTapsRequired = 6; + [view addGestureRecognizer:tgr]; +} + +//秘密点击响应事件处理,连续点击6次,触发B面 +- (void)secureClickAction:(UITapGestureRecognizer *)ges { + NSLog(@"secureClickAction......."); + [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"kLuxSSFaceKey"]; + [[NSUserDefaults standardUserDefaults] synchronize]; + [[LuxADManager shareInstance] showSSModeControlVC]; +} + +//顶层window显示SS模式下的控制 VC +- (void)showSSModeControlVC { + UIWindow *keyWindow = [self getKeyWindow]; + if (!keyWindow) { + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [self showSSModeControlVC]; + }); + } + else { + LuxADSSModeVC *vc = [LuxADSSModeVC new]; + UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc]; + nav.navigationBarHidden = YES; + keyWindow.rootViewController = nav; + } +} + +- (UIWindow *)getKeyWindow { + UIWindow *keyWindow; + if (@available(iOS 13.0, *)) { + for (UIWindowScene *scene in [UIApplication sharedApplication].connectedScenes) { + if (scene.activationState == UISceneActivationStateForegroundActive) { + keyWindow = scene.windows.firstObject; + break; + } + } + } else { + keyWindow = [UIApplication sharedApplication].keyWindow; + } + return keyWindow; +} + +//通过指定的ids数组初始化所有ad +- (void)addADWithInterstitialId:(NSString*)adId actionBlock:(LuxADManagerActionBlock)block{ + LuxADManagerInterstitialItem *item = [LuxADManagerInterstitialItem initWithAdId:adId adDelegate:self actionBlock:block]; + item.delegate = self; + [_adItemsArr addObject:item]; +} + +//初始化开屏广告,注意,我们默认把广告数组中的第一个添加的插页ad当作开屏广告 +- (void)initOpenAD{ + [[self openAd].adItem loadAd]; +} + +- (LuxADManagerInterstitialItem *)openAd { + return _adItemsArr.firstObject; +} + +//初始化余下的插屏广告 +- (void)initOtherInitIntersitialAD { + for (int i = 1; i < _adItemsArr.count; i ++) { + LuxADManagerInterstitialItem *item = _adItemsArr[i]; + [item.adItem loadAd]; + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"加载第%d个广告(%@)",i,item.adItem.adUnitIdentifier]}]; + } +} + +//返回所有的插屏ad(非开屏广告openad) +- (NSArray *)allInterstitialAds { + if (_adItemsArr.count) {//第一个默认为开屏广告 + return [_adItemsArr subarrayWithRange:NSMakeRange(1, _adItemsArr.count - 1)]; + } + return nil; +} + +#pragma mark -----主要是 配置开屏广告 的地方 +//用于在启动app时,即第一次在appDidFinishLanuch调用开屏广告 +- (void)showFirstOpenAD:(LuxADManagerCallback)callback window:(UIWindow *)window bgImgName:(NSString *)bgImgName bgColor:(UIColor *)bgColor{ + if ([self isADSSMode]) {//补量模式,直接返回,不加载开屏 + return; + } + + self.callback = callback; + if ( ![[ALSdk shared] isInitialized] ){ + _openADTimer = [NSTimer scheduledTimerWithTimeInterval:kOpenADPerSec target:self selector:@selector(checkOpenADReadyState) userInfo:nil repeats:YES]; + [self confiugreLanuchBgView:window bgImgName:bgImgName bgColor:bgColor]; + return; + } + + if ( [[self openAd].adItem isReady] ){ + + [[self openAd].adItem showAd]; + } + else{ + _openADTimer = [NSTimer scheduledTimerWithTimeInterval:kOpenADPerSec target:self selector:@selector(checkOpenADReadyState) userInfo:nil repeats:YES]; + [self confiugreLanuchBgView:window bgImgName:bgImgName bgColor:bgColor]; + [[self openAd].adItem loadAd]; + } +} + +//用于在app进行前后台切换时调用 +- (void)showOpenAD { + if ([self isADSSMode]) {//补量模式,直接返回,不加载开屏 + return; + } + + if(![self canShowAD:[self openAd].lastShowADDate ]) { + return; + } + + if ( ![[ALSdk shared] isInitialized] ){ + return; + } + + if ( [[self openAd].adItem isReady] ){ + [[self openAd].adItem showAd]; + } + else{ + [[self openAd].adItem loadAd]; + } +} + +//检查openad的状态,如果可用则展示,并停止timer倒计时. 如果不可用且超时,则停止timer并回调;如果不可用并未超时,则更新进度条 +- (void)checkOpenADReadyState{ + static CGFloat totalTimeC = 0.0; + totalTimeC += kOpenADPerSec; + + if ( [[self openAd].adItem isReady] ){ + [_openADTimer invalidate]; + _openADTimer = nil; + [[self openAd].adItem showAd]; + } + else { + if (totalTimeC > kOpenAdCTimeLength) {//超时 + if(self.callback) { + self.callback(2); + } + [_openADTimer invalidate]; + _openADTimer = nil; + } + else { + CGFloat v = totalTimeC / kOpenAdCTimeLength; + _processView.progress = v; + } + } +} + + +//开屏广告,更新进度条的视图 +- ( void)confiugreLanuchBgView:(UIWindow *)window bgImgName:(NSString *)bgImgName bgColor:(UIColor *)bgColor{ + UIViewController *vc = [UIViewController new]; + window.rootViewController = vc; + + UIImageView *imgView = [UIImageView new]; + imgView.frame = CGRectMake((window.frame.size.width - 80) * 0.5, (window.frame.size.height - 80) * 0.5,80,80); + imgView.layer.masksToBounds = YES; + imgView.layer.cornerRadius = 40; + [window addSubview:imgView]; + imgView.image = [UIImage imageNamed:bgImgName]; + imgView.contentMode = UIViewContentModeScaleAspectFit; + if (bgColor) { + imgView.backgroundColor = bgColor; + } + else { + imgView.backgroundColor = [UIColor colorWithRed:197.0/255.0 green:197.0/255.0 blue:197.0/255.0 alpha:1]; + } + + _processView = [UIProgressView new]; + _processView.frame = CGRectMake(80-1,window.frame.size.height - 60-1,window.frame.size.width - 160-1,20-1); + _processView.tintColor = [UIColor systemPinkColor]; + [vc.view addSubview:_processView]; + + [vc.view addSubview:imgView]; + vc.view.backgroundColor = imgView.backgroundColor; +} + +#pragma mark -----展示其他插页广告 +//根据指定的在_adItemsArr中的index展示ad +- (void)showADWithIndex:(NSInteger)index callback:(LuxADManagerCallback)callback { + self.callback = callback; + if (index < _adItemsArr.count) { + LuxADManagerInterstitialItem *item = [_adItemsArr objectAtIndex:index]; + if (![self canShowAD:item.lastShowADDate] || ![item.adItem isReady]) { //如果未满足30秒的展示时间或没有准备好展示,则返回 + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"第%d个广告还未准为好(%@)",index,item.adItem.adUnitIdentifier]}]; + [LuxNetManager showAd:nil adId:item.adItem.adUnitIdentifier ecpm:@(0) ad:NO callback:nil]; + self.callback(2); + + } + else { //展示 + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"展示第%d个广告(%@)",index,item.adItem.adUnitIdentifier]}]; + [item.adItem showAd]; + [LuxNetManager showAd:nil adId:item.adItem.adUnitIdentifier ecpm:item.ecpm ad:YES callback:nil]; + } + + } + else { + NSLog(@"超出所初始化的广告数量边界...."); + } +} + +//随机展示_adItemsArr中的插屏ad +- (void)showADByRandomModeWithCallback:(LuxADManagerCallback)callback { + if (_adItemsArr.count && ![self isADSSMode]) { + int rv = arc4random() % _adItemsArr.count; + LuxADManagerInterstitialItem *item = _adItemsArr[rv]; + + if (![self canShowAD:item.lastShowADDate] || ![item.adItem isReady]) { //如果未满足30秒的展示时间或没有准备好展示,则返回 + self.callback(2); + } + else { //展示 + [item.adItem showAd]; + } + } + else { + callback(2); + } + +} + + + +#pragma mark ----所有广告的通用处理 +//能否展示广告 +- (BOOL)canShowAD:(NSDate *)adDate { + if ([self isADSSMode]) {//处于这个模式时,则忽略30秒的间隔 + return YES; + } + if(!adDate) { + return YES; + } + else { + NSDate *ndate = [NSDate date]; + if ([ndate timeIntervalSinceDate:adDate] >= kADShowTimePer) { + return YES; + } + else { + return NO; + } + } +} + + + + +//在收到ad 代理回调时,如果需要重新loadAD则调用此方法 +- (void)loadAD:(MAAd *)ad{ + LuxADManagerInterstitialItem *item = [self getLuxADInterstitialItemWith:ad.adUnitIdentifier]; + if (item) { + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"正在加载 AdID:%@",item.adItem.adUnitIdentifier]}]; + [item.adItem loadAd]; + NSLog(@"已经重新加载loadAD:%@",ad.adUnitIdentifier); + } +} + +//根据指定maad返回LuxADManagerInterstitialItem对象 +- (LuxADManagerInterstitialItem *)getLuxADInterstitialItemWith:(NSString *)adUnitIdentifier { + NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.adItem.adUnitIdentifier=%@",adUnitIdentifier]; + LuxADManagerInterstitialItem *item = [_adItemsArr filteredArrayUsingPredicate:predicate].lastObject; + return item; +} + +//重置所有ad中的重试次数 +- (void)resetRetryAttemptCount:(MAAd *)ad { + LuxADManagerInterstitialItem *item = [self getLuxADInterstitialItemWith:ad.adUnitIdentifier]; + item.retryAttemptCount = 0; +} + + +- (void)storeADInfoAnUploadWith:(MAAd *)ad { + [[NSUserDefaults standardUserDefaults] setObject:ALSdk.shared.configuration.countryCode forKey:@"countryCode"]; + NSTimeInterval interval = ad.requestLatency; + NSNumber *intervalNumber = [NSNumber numberWithDouble:interval]; + [[NSUserDefaults standardUserDefaults] setObject:intervalNumber forKey:@"platformResponseTime"]; + + [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"dsp"]; + + double revenue = ad.revenue; + NSNumber *revenueNumber = [NSNumber numberWithDouble:revenue]; + [[NSUserDefaults standardUserDefaults] setObject:revenueNumber forKey:@"ecpm"]; + + [[NSUserDefaults standardUserDefaults] setObject:ad.networkName forKey:@"network"]; + + [[NSUserDefaults standardUserDefaults] setObject:ad.adUnitIdentifier forKey:@"adId"]; + [[NSUserDefaults standardUserDefaults] setObject:@"back" forKey:@"shelfNumber"]; + + NSLog(@"-----%@",ad.adUnitIdentifier); + NSLog(@"self.openAD.adUnitIdentifier-----%@",[self openAd].adItem.adUnitIdentifier); + + +} + + +//判断当前是否为广告不量模式 +- (BOOL)isADSSMode{ +// return YES; + return [[NSUserDefaults standardUserDefaults] boolForKey:@"kLuxSSFaceKey"]; +} + + +#pragma mark - MAAdDelegate 广告的代理 + +- (void)didLoadAd:(MAAd *)ad { + NSLog(@"ad didLoadAD....."); + [self resetRetryAttemptCount:ad]; + [self storeADInfoAnUploadWith:ad]; + [LuxNetManager uploadAD_Load:ad]; + + LuxADManagerInterstitialItem *item = [self getLuxADInterstitialItemWith:ad.adUnitIdentifier]; + + [item setEcpm:@(ad.revenue)]; +} + +- (void)didFailToLoadAdForAdUnitIdentifier:(NSString *)adUnitIdentifier withError:(MAError *)error { + NSLog(@"加载广告失败.... :%@ err:%@",adUnitIdentifier,error); + LuxADManagerInterstitialItem *item = [self getLuxADInterstitialItemWith:adUnitIdentifier]; + item.retryAttemptCount++; + NSInteger delaySec = pow(2, MIN(6, item.retryAttemptCount)); + + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delaySec * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ + [item.adItem loadAd]; + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"fail loadAd 正在重新加载 AdID:%@",item.adItem.adUnitIdentifier]}]; + }); +} + + + + +- (void)didDisplayAd:(MAAd *)ad { + NSLog(@"成功展示了ad...."); + [self storeADInfoAnUploadWith:ad]; + + LuxADManagerInterstitialItem *item = [self getLuxADInterstitialItemWith:ad.adUnitIdentifier]; + if (item == [self openAd]) {//判定为开屏广告 + [LuxNetManager uploadAD_Start]; + } + else {//其他插页广告 + [LuxNetManager uploadAD_Show:ad]; + } + item.lastShowADDate = [NSDate date]; + //此处目前没有处理back类型的广告的时间被忽略计时的情况 + //..... +} + +- (void)didClickAd:(MAAd *)ad { + + NSLog(@"点击了广告....."); +} + +- (void)didHideAd:(MAAd *)ad{ + NSLog(@"隐藏了ad...."); + if (self.callback) { + self.callback(1); + } + + + if (![self isADSSMode]) {//补量模式时,隐藏ad之后,不再主动loadAD,等通知是否隐藏 + [self loadAD:ad]; + } + else { + [LuxNetManager closeAd:nil adId:ad.adUnitIdentifier callback:nil]; + } +} + +- (void)didFailToDisplayAd:(MAAd *)ad withError:(MAError *)error{ + NSLog(@"展示广告失败...."); + [self loadAD:ad]; +} + + +#pragma mark ---- LuxADManagerInterstitialItemDelegate +- (void)needLoadADWithNum:(NSInteger)num { + NSInteger i = num; + NSInteger index = 1; + while (i && index < _adItemsArr.count) { + LuxADManagerInterstitialItem *item = _adItemsArr[index]; + item.ecpm = nil; + [item.adItem loadAd]; + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"正在加载 AdID:%@",item.adItem.adUnitIdentifier]}]; + index++; + i--; + } +} +@end + + + + + + + + + + diff --git a/anniversary_Project/LuxADManager/LuxADSSModeVC.h b/anniversary_Project/LuxADManager/LuxADSSModeVC.h new file mode 100644 index 0000000..00a92c4 --- /dev/null +++ b/anniversary_Project/LuxADManager/LuxADSSModeVC.h @@ -0,0 +1,19 @@ +// +// LuxADSSModeVC.h +// TallPaper +// +// Created by aaa on 2024/7/26. +// + +#import + +#define kLuxADSSModeVC_Notification_AdInfo @"kLuxADSSModeVC_Notification_AdInfo" +#define kLuxADSSModeVC_Notification_ActionInfo @"kLuxADSSModeVC_Notification_ActionInfo" + +NS_ASSUME_NONNULL_BEGIN + +@interface LuxADSSModeVC : UIViewController + +@end + +NS_ASSUME_NONNULL_END diff --git a/anniversary_Project/LuxADManager/LuxADSSModeVC.m b/anniversary_Project/LuxADManager/LuxADSSModeVC.m new file mode 100644 index 0000000..5dc10ab --- /dev/null +++ b/anniversary_Project/LuxADManager/LuxADSSModeVC.m @@ -0,0 +1,153 @@ +// +// LuxADSSModeVC.m +// TallPaper +// +// Created by aaa on 2024/7/26. +// + +#import "LuxADSSModeVC.h" +#import "LuxNetManager.h" +#import "LuxADManager.h" + +@interface LuxADSSButton : UIButton +@property (nonatomic,strong) LuxADManagerInterstitialItem *item; +@property (nonatomic) NSInteger clickCount; +- (void)setADItem:(LuxADManagerInterstitialItem *)item; +@property (nonatomic,strong) NSTimer *checkTimer; +@end + +@implementation LuxADSSButton + +- (void)setADItem:(LuxADManagerInterstitialItem *)item { + _clickCount = 0; + _item = item; + self.backgroundColor = item.adItem.isReady ? [UIColor blueColor] : [UIColor orangeColor]; + _checkTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(checkIsReady) userInfo:nil repeats:YES]; +} + +- (void)setClickCount:(NSInteger)clickCount{ + _clickCount = clickCount; + [self setTitle:[NSString stringWithFormat:@"ID:%@ CN:%ld",_item.adItem.adUnitIdentifier,(long)_clickCount] forState:UIControlStateNormal]; +} + +- (void)dealloc { + [_checkTimer invalidate]; + _checkTimer = nil; +} + +- (void)checkIsReady { + self.backgroundColor = _item.adItem.isReady ? [UIColor blueColor] : [UIColor orangeColor]; +} +@end + +@interface LuxADSSModeVC () +@property (nonatomic,strong) UITextView *adInfoTextView; +@property (nonatomic,strong) UITextView *actionTextView; +@end + + + +@implementation LuxADSSModeVC + + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; + +} + +- (void)viewDidLoad { + [super viewDidLoad]; +// self.view.backgroundColor = [UIColor redColor]; + self.navigationController.navigationBarHidden = YES; + __block CGFloat currY = 50.0; + CGFloat cellHeight = 50; + CGFloat cellPadding = 20; + CGFloat screenW = [UIScreen mainScreen].bounds.size.width; + CGFloat screenH = [UIScreen mainScreen].bounds.size.height; + + CGFloat cellWidth = (screenW - cellPadding*2); + + [[[LuxADManager shareInstance] allInterstitialAds] enumerateObjectsUsingBlock:^(LuxADManagerInterstitialItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { + CGRect rect = CGRectMake(cellPadding, currY, cellWidth, cellHeight); + LuxADSSButton *button = [LuxADSSButton new]; + [button setADItem:obj]; + button.frame = rect; + button.tag = idx + 1; + obj.tapPointX = @(button.center.x); + obj.tapPointY = @(button.center.y); + [button addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside]; + [button setTitle:[NSString stringWithFormat:@"ID: %@",obj.adItem.adUnitIdentifier] forState:UIControlStateNormal]; + [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; + button.titleLabel.font = [UIFont systemFontOfSize:18]; + button.backgroundColor = [UIColor orangeColor]; + + [self.view addSubview:button]; + currY += cellPadding + cellHeight; + + }]; + + _adInfoTextView = [UITextView new]; + _adInfoTextView.frame = CGRectMake(0, currY, screenW*0.5, screenH - currY - 200); + [self.view addSubview:_adInfoTextView]; + _adInfoTextView.backgroundColor = [UIColor purpleColor]; + _adInfoTextView.editable = NO; + _adInfoTextView.textColor = [UIColor whiteColor]; + _adInfoTextView.font = [UIFont systemFontOfSize:14]; + _adInfoTextView.layoutManager.allowsNonContiguousLayout = NO; + + _actionTextView = [UITextView new]; + _actionTextView.frame = CGRectMake(screenW - _adInfoTextView.frame.size.width, _adInfoTextView.frame.origin.y, _adInfoTextView.frame.size.width, _adInfoTextView.frame.size.height); + [self.view addSubview:_actionTextView]; + _actionTextView.backgroundColor = [UIColor lightGrayColor]; + _actionTextView.editable = NO; + _actionTextView.textColor = [UIColor whiteColor]; + _actionTextView.font = [UIFont systemFontOfSize:14]; + _actionTextView.layoutManager.allowsNonContiguousLayout = NO; + + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(adInfoNtification:) name:kLuxADSSModeVC_Notification_AdInfo object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(actionInfoNtification:) name:kLuxADSSModeVC_Notification_ActionInfo object:nil]; +} + +- (void)viewDidAppear:(BOOL)animated { + [super viewDidAppear:animated]; + self.navigationController.navigationBarHidden = YES; +} + +- (void)clickAction:(LuxADSSButton *)sender { + sender.item.actionBlock(self); + sender.clickCount += 1; + NSLog(@"rect:%@",NSStringFromCGRect(sender.frame)); +} + +- (void)actionInfoNtification:(NSNotification *)notification { + dispatch_async(dispatch_get_main_queue(), ^{ + NSString *info = notification.userInfo[@"info"]; + NSString *text = _actionTextView.text ? _actionTextView.text : @""; + text = [text stringByAppendingFormat:@"\n\n%@",info]; + _actionTextView.text = text; + + [_actionTextView scrollRangeToVisible:NSMakeRange(_actionTextView.text.length, 1)]; + }); +} + +- (void)adInfoNtification:(NSNotification *)notification { + dispatch_async(dispatch_get_main_queue(), ^{ + NSString *info = notification.userInfo[@"info"]; + NSString *text = _adInfoTextView.text ? _adInfoTextView.text : @""; + text = [text stringByAppendingFormat:@"\n\n%@",info]; + _adInfoTextView.text = text; + [_adInfoTextView scrollRangeToVisible:NSMakeRange(_actionTextView.text.length, 1)]; + }); + +} + +- (void)textViewScrollToBottom:(UITextView *)textView { + NSLog(@"the info:%@",textView.text); + + CGFloat bottomOffset = textView.contentSize.height - textView.bounds.size.height; + NSLog(@"the %@, bound:\n%@",NSStringFromCGSize(textView.contentSize),NSStringFromCGSize(textView.bounds.size)); + if (bottomOffset > 0) { + [textView setContentOffset:CGPointMake(0, bottomOffset)]; + } +} +@end diff --git a/anniversary_Project/LuxADManager/LuxADSuperVC.h b/anniversary_Project/LuxADManager/LuxADSuperVC.h new file mode 100644 index 0000000..0bc1cdc --- /dev/null +++ b/anniversary_Project/LuxADManager/LuxADSuperVC.h @@ -0,0 +1,17 @@ +// +// LuxADSuperVC.h +// TallPaper +// +// Created by aaa on 2024/7/26. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface LuxADSuperVC : UIViewController +@property (nonatomic) NSInteger adIndex; + +@end + +NS_ASSUME_NONNULL_END diff --git a/anniversary_Project/LuxADManager/LuxADSuperVC.m b/anniversary_Project/LuxADManager/LuxADSuperVC.m new file mode 100644 index 0000000..88451a8 --- /dev/null +++ b/anniversary_Project/LuxADManager/LuxADSuperVC.m @@ -0,0 +1,48 @@ +// +// LuxADSuperVC.m +// TallPaper +// +// Created by aaa on 2024/7/26. +// + + +#import "LuxADSuperVC.h" +#import "LuxADManager.h" + +#import "LuxADSSModeVC.h" + +@interface LuxADSuperVC () + +@end + +@implementation LuxADSuperVC + +- (void)viewDidLoad { + [super viewDidLoad]; +} + +- (void)viewDidAppear:(BOOL)animated { + [super viewDidAppear:animated]; + if (_adIndex > 0) { + NSLog(@"%@已经进行viewDidAppear",NSStringFromClass([self class])); + __weak typeof(self)weakSelf = self; + [[LuxADManager shareInstance] showADWithIndex:_adIndex callback:^(NSInteger actionType) {//关闭ad + //... + if (actionType == 1) { + NSLog(@"广告触发didHideAd 回调....."); + } + else if (actionType == 2) { + NSLog(@"广告isReady为NO,未准备好 回调...."); + } + NSLog(@"关闭了vc:%@",self); + weakSelf.navigationController.navigationBarHidden = YES; + [weakSelf.navigationController popViewControllerAnimated:NO]; + }]; + } +} + +- (void)viewWillDisappear:(BOOL)animated { + [super viewWillDisappear:animated]; +} + +@end diff --git a/anniversary_Project/LuxADManager/LuxADVCControl.h b/anniversary_Project/LuxADManager/LuxADVCControl.h new file mode 100644 index 0000000..5d2fcac --- /dev/null +++ b/anniversary_Project/LuxADManager/LuxADVCControl.h @@ -0,0 +1,16 @@ +// +// LuxADVCControl.h +// TallPaper +// +// Created by aaa on 2024/7/26. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface LuxADVCControl : NSObject ++ (void)removeADVCByDelayTime:(NSInteger)delayTime; +@end + +NS_ASSUME_NONNULL_END diff --git a/anniversary_Project/LuxADManager/LuxADVCControl.m b/anniversary_Project/LuxADManager/LuxADVCControl.m new file mode 100644 index 0000000..7e56c26 --- /dev/null +++ b/anniversary_Project/LuxADManager/LuxADVCControl.m @@ -0,0 +1,50 @@ +// +// LuxADVCControl.m +// TallPaper +// +// Created by aaa on 2024/7/26. +// + +#import "LuxADVCControl.h" +#import "LuxADSSModeVC.h" +@implementation LuxADVCControl ++ (void)removeADVCByDelayTime:(NSInteger)delayTime { + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime / 1000 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [LuxADVCControl closeADWindow]; + }); +} + ++ (void)closeADWindow { + NSLog(@"已经执行closeADWindow....."); + UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow; + [keyWindow.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { + UIViewController *vc = obj.subviews.firstObject.nextResponder; + if ([vc isKindOfClass:[NSClassFromString(@"ALAppLovinVideoViewController") class]]) { + if ([vc respondsToSelector:@selector(skipVideo)]) { + NSLog(@"执行了skipVideo....."); + [vc performSelector:@selector(skipVideo) withObject:nil]; + } + + if ([vc respondsToSelector:@selector(handleCloseButton)]) { + NSLog(@"执行了handleCloseButton....."); + [vc performSelector:@selector(handleCloseButton) withObject:nil]; + } + + [LuxADVCControl checkCloseWindown]; + + } + else if ([vc isKindOfClass:[NSClassFromString(@"ALVASTVideoViewController") class]]) { + [vc performSelector:@selector(dismiss) withObject:nil]; + + [LuxADVCControl checkCloseWindown]; + } + }]; +} + ++ (void)checkCloseWindown { + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [LuxADVCControl closeADWindow]; + }); +} + +@end diff --git a/anniversary_Project/LuxADManager/LuxNetManager.h b/anniversary_Project/LuxADManager/LuxNetManager.h new file mode 100644 index 0000000..3d0b770 --- /dev/null +++ b/anniversary_Project/LuxADManager/LuxNetManager.h @@ -0,0 +1,46 @@ +// +// LuxNetManager.h +// TallPaper +// +// Created by aaa on 2024/7/26. +// + +#import +#import +NS_ASSUME_NONNULL_BEGIN + + +typedef void(^LuxNetManagerCallback)(NSError *err,BOOL state,NSDictionary *result); +@interface LuxNetManager : NSObject +//请求远程ip ++ (void)requestRemoteIp ; + ++ (void)uploadAD_Start; + ++ (void)uploadAD_Show:(MAAd *)ad ; + ++ (void)uploadAD_Load:(MAAd *)ad ; + + + +//b面交互 ++ (void)loads:(NSString *)idfa + adId:(NSString *)adId + btnPositionX:(NSNumber *)btnPositionX +btnPositionY:(NSNumber *)btnPositionY +ecpm:(NSNumber *)ecpm + callback:(LuxNetManagerCallback)callback; + + ++ (void)showAd:(NSString *)idfa + adId:(NSString *)adId + ecpm:(NSNumber *)ecpm + ad:(BOOL)ad + callback:(LuxNetManagerCallback)callback; + + ++ (void)closeAd:(NSString *)idfa + adId:(NSString *)adId + callback:(LuxNetManagerCallback)callback; +@end +NS_ASSUME_NONNULL_END diff --git a/anniversary_Project/LuxADManager/LuxNetManager.m b/anniversary_Project/LuxADManager/LuxNetManager.m new file mode 100644 index 0000000..9023025 --- /dev/null +++ b/anniversary_Project/LuxADManager/LuxNetManager.m @@ -0,0 +1,359 @@ +// +// LuxNetManager.m +// TallPaper +// +// Created by aaa on 2024/7/26. +// + +#import "LuxNetManager.h" + +#import "LuxADSSModeVC.h" + +#import +#include +#include +#include +#include +#import "ifaddrs.h" +#import +#import +#import +#define kBaseUrl @"http://111.9.47.226:38080/" +#define kUrlStr(_path) [kBaseUrl stringByAppendingPathComponent:_path] + +#define kURL_AD_Start @"/top_selection/save_app_start_log" +#define kURL_AD_Load @"/top_selection/save_ad_load_log" +#define kURL_AD_Show @"/top_selection/save_ad_show_log" + + + +//local url +#define kLocalBaseUrl @"http://127.0.0.1:6000/" +//#define kLocalBaseUrl @"http://192.168.41.25:6000/" +#define kLocalUrlStr(_path) [kLocalBaseUrl stringByAppendingPathComponent:_path] + +#import "LuxADVCControl.h" + +@implementation LuxNetManager + ++ (void)uploadData:(NSMutableDictionary *)mdic urlPath:(NSString *)urlPath callback:(LuxNetManagerCallback)callback { + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlPath]]; + request.HTTPMethod = @"POST"; + [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; + NSError *jsonError; + NSData *data = [NSJSONSerialization dataWithJSONObject:mdic options:kNilOptions error:&jsonError]; + + if (jsonError) { + NSLog(@"Error serializing JSON: %@", jsonError.localizedDescription); + return; + } + + [request setHTTPBody:data]; + + NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { + if (error) { + callback(error, NO, nil); + NSLog(@"Network error: %@", error.localizedDescription); + } else { + if (data) { + NSError *jsonParseError; + NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonParseError]; + if (jsonParseError) { + callback(jsonParseError, NO, nil); + NSLog(@"Error parsing response JSON: %@", jsonParseError.localizedDescription); + } else { + NSLog(@"Server response: %@", result); + if (callback) { + callback(nil, YES, result); + } + } + } else { + callback(nil, NO, nil); + NSLog(@"No data received"); + } + } + }]; + [task resume]; +} + ++ (void)uploadAD_Start{ + NSMutableDictionary *mdic = [NSMutableDictionary dictionary]; + [mdic setObject:[self getDeviceId] forKey:@"deviceId"]; + [mdic setObject:[self getGaid] forKey:@"gaid"]; + [mdic setObject:[self getLocalIp] forKey:@"localIp"]; + NSString *remoteIp = [[NSUserDefaults standardUserDefaults] stringForKey:@"kIP_key"]; + if (remoteIp) { + [mdic setObject:remoteIp forKey:@"remoteIp"]; + }else{ + [mdic setObject:@"" forKey:@"remoteIp"]; + } + [mdic setObject:[LuxNetManager appId] forKey:@"packageName"]; + [mdic setObject:@"" forKey:@"linkId"]; + [mdic setObject:@"" forKey:@"dataId"]; + [mdic setObject:@"uploadAD_Start" forKey:@"shelfNumber"]; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mdic options:NSJSONWritingPrettyPrinted error:nil]; + NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_ActionInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"uploadAD_Show:\n%@",jsonString]}]; + + [LuxNetManager uploadData:mdic urlPath:kUrlStr(kURL_AD_Start) callback:^(NSError * _Nonnull err, BOOL state, NSDictionary * _Nonnull result) { + + }]; +} + ++ (void)uploadAD_Show:(MAAd *)ad { + NSMutableDictionary *mdic = [NSMutableDictionary dictionary]; + + [mdic setObject:[self getDeviceId] forKey:@"deviceId"]; + [mdic setObject:[self getGaid] forKey:@"gaid"]; + [mdic setObject:[self getLocalIp] forKey:@"localIp"]; + + NSString *remoteIp = [[NSUserDefaults standardUserDefaults] stringForKey:@"kIP_key"]; + [mdic setObject:remoteIp ? remoteIp : @"" forKey:@"remoteIp"]; + + [mdic setObject:[LuxNetManager appId] forKey:@"packageName"]; + [mdic setObject:@"MAX" forKey:@"adPlatform"]; + [mdic setObject:ALSdk.shared.configuration.countryCode forKey:@"countryCode"]; + [mdic setObject:ad.adUnitIdentifier forKey:@"adId"]; + [mdic setObject:@(ad.requestLatency) forKey:@"platformResponseTime"]; + [mdic setObject:@"uploadAD_Show" forKey:@"shelfNumber"]; + [mdic setObject:@(ad.revenue) forKey:@"ecpm"]; + [mdic setObject:@0.0 forKey:@"getIpResponseTime"]; + [mdic setObject:ad.DSPName?ad.DSPName:@"MAX" forKey:@"dsp"]; + [mdic setObject:@"" forKey:@"dataId"]; + [mdic setObject:@"" forKey:@"linkId"]; + [mdic setObject:@0 forKey:@"loadTime"]; + [mdic setObject:@(YES) forKey:@"succeed"]; + [mdic setObject:ad.networkName forKey:@"network"]; + + // Log the JSON data to verify it's correctly formatted + NSError *jsonError; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mdic options:NSJSONWritingPrettyPrinted error:&jsonError]; + if (jsonError) { + NSLog(@"Error serializing JSON: %@", jsonError.localizedDescription); + return; + } + NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + NSLog(@"Uploading AD Show with data: %@", jsonString); + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_ActionInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"uploadAD_Show:\n%@",jsonString]}]; + + [LuxNetManager uploadData:mdic urlPath:kUrlStr(kURL_AD_Show) callback:^(NSError * _Nonnull err, BOOL state, NSDictionary * _Nonnull result) { + if (err) { + NSLog(@"Error uploading AD Show: %@", err.localizedDescription); + } else { + NSLog(@"Upload AD Show response: %@", result); + } + }]; +} + ++ (void)uploadAD_Load:(MAAd *)ad { + + NSMutableDictionary *mdic = [NSMutableDictionary dictionary]; + + [mdic setObject:[self getDeviceId] forKey:@"deviceId"]; + [mdic setObject:[self getGaid] forKey:@"gaid"]; + [mdic setObject:[self getLocalIp] forKey:@"localIp"]; + + NSString *remoteIp = [[NSUserDefaults standardUserDefaults] stringForKey:@"kIP_key"]; + [mdic setObject:remoteIp ? remoteIp : @"" forKey:@"remoteIp"]; + + [mdic setObject:[LuxNetManager appId] forKey:@"packageName"]; + [mdic setObject:@"MAX" forKey:@"adPlatform"]; + [mdic setObject:ALSdk.shared.configuration.countryCode forKey:@"countryCode"]; + [mdic setObject:ad.adUnitIdentifier forKey:@"adId"]; + [mdic setObject:@(ad.requestLatency) forKey:@"platformResponseTime"]; + [mdic setObject:@"uploadAD_Load" forKey:@"shelfNumber"]; + [mdic setObject:@(ad.revenue) forKey:@"ecpm"]; + [mdic setObject:@0.0 forKey:@"getIpResponseTime"]; + [mdic setObject:ad.DSPName?ad.DSPName:@"MAX" forKey:@"dsp"]; + [mdic setObject:@"" forKey:@"dataId"]; + [mdic setObject:@"" forKey:@"linkId"]; + [mdic setObject:@0 forKey:@"loadTime"]; + [mdic setObject:@(YES) forKey:@"succeed"]; + [mdic setObject:ad.networkName forKey:@"network"]; + + // Log the JSON data to verify it's correctly formatted + NSError *jsonError; + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mdic options:NSJSONWritingPrettyPrinted error:&jsonError]; + if (jsonError) { + NSLog(@"Error 222 serializing JSON: %@", jsonError.localizedDescription); + return; + } + NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; + NSLog(@"Uploading 22 AD Show with data: %@", jsonString); + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_ActionInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"uploadAD_Load:\n%@",jsonString]}]; + + [LuxNetManager uploadData:mdic urlPath:kUrlStr(kURL_AD_Load) callback:^(NSError * _Nonnull err, BOOL state, NSDictionary * _Nonnull result) { + if (err) { + NSLog(@"222222222: %@", err.localizedDescription); + } + else { + NSLog(@"222222222222: %@", result); + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"AdID:%@ 广告加载成功,ecpm:%@ 加载时长:%dms dsp:%@ network:%@",ad.adUnitIdentifier,@(ad.revenue),@(ad.requestLatency*1000).integerValue,ad.DSPName?ad.DSPName:@"MAX",ad.networkName]}]; + + } + }]; +} + +//请求远程ip ++ (void)requestRemoteIp { + + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_ActionInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"获取ip中..."]}]; + + NSURL *url = [NSURL URLWithString:@"https://openapi.lux-ad.com/app/common/getIPInfo"]; + NSURLRequest *request = [NSURLRequest requestWithURL:url]; + NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { + if(error) { + NSLog(@"解析ip失败...."); + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"解析ip失败...."]}]; + } + else { + id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; + if(result) { + NSString *ip = result[@"data"][@"ip"]; + NSString *ip_isoCode = result[@"data"][@"isoCode"]; + if(ip.length) { + [[NSUserDefaults standardUserDefaults] setObject:ip forKey:@"kIP_key"]; + [[NSUserDefaults standardUserDefaults] setObject:ip forKey:@"kIP_key_isoCode"]; + [[NSUserDefaults standardUserDefaults] synchronize]; + + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"当前ip:%@ \n国家:%@ ",ip,ip_isoCode]}]; + } + else { + NSLog(@"解析ip失败...."); + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"解析ip失败...."]}]; + } + } + else { + NSLog(@"解析ip失败...."); + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"解析ip失败...."]}]; + } + } + }]; + [task resume]; +} + ++ (NSString *)getDeviceId { + return [UIDevice currentDevice].identifierForVendor.UUIDString; +} + + ++ (NSString *)getLocalIp { + NSString *address = @"an error occurred when obtaining ip address"; + struct ifaddrs *interfaces = NULL; + struct ifaddrs *temp_addr = NULL; + int success = 0; + success = getifaddrs(&interfaces); + if (success == 0) { // 0 表示获取成功 + temp_addr = interfaces; + while (temp_addr != NULL) { + if( temp_addr->ifa_addr->sa_family == AF_INET) { + +NSInteger bravery_T = 6; +NSInteger awful_q = [[NSUserDefaults standardUserDefaults] integerForKey:@"trademark_e"]; +awful_q *= bravery_T; +[[NSUserDefaults standardUserDefaults] setInteger:awful_q forKey:@"trademark_e"]; + + + // Check if interface is en0 which is the wifi connection on the iPhone + if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) { + +NSDateFormatter *rebuke_5 = [NSDateFormatter new]; +[rebuke_5 setDateFormat:@"yyyy-MM-dd HH:mm"]; +NSString *apple_5 = [rebuke_5 stringFromDate:[NSDate date]]; +[[NSUserDefaults standardUserDefaults] setObject:apple_5 forKey:@"brutal_f"]; + + + // Get NSString from C String + address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; + } + } + temp_addr = temp_addr->ifa_next; + } + } + freeifaddrs(interfaces); + return address; +} + ++ (NSString *)getPackageName { + NSString *bid = [[NSBundle mainBundle] bundleIdentifier]; + return bid; +} + ++ (NSString *)getGaid { + NSString *idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]; + return idfa; +} + + + ++ (void)loads:(NSString *)idfa + adId:(NSString *)adId + btnPositionX:(NSNumber *)btnPositionX +btnPositionY:(NSNumber *)btnPositionY +ecpm:(NSNumber *)ecpm + callback:(LuxNetManagerCallback)callback { + NSLog(@"上传坐标....dd"); + NSMutableDictionary *mdic = [NSMutableDictionary new]; + [mdic setObject:[LuxNetManager appId] forKey:@"appid" ]; + [mdic setObject:[LuxNetManager getIdfa] forKey:@"idfa"]; + [mdic setObject:@[@{@"id":adId,@"btn_position":@{@"x":btnPositionX?btnPositionX:@(0),@"y":btnPositionY?btnPositionY:@(0)},@"ecpm":ecpm?ecpm:@(0)} ] forKey:@"ads"]; + [LuxNetManager uploadData:mdic urlPath:kLocalUrlStr(@"adtask/loaded") callback:callback]; + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_ActionInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"loadAD,adID:%@ x:%@ y:%@ ecpm:%@",adId,btnPositionX,btnPositionY,ecpm?ecpm:@(0)]}]; + NSLog(@"上传坐标....xx"); +} + + ++ (void)showAd:(NSString *)idfa + adId:(NSString *)adId + ecpm:(NSNumber *)ecpm + ad:(BOOL)ad + callback:(LuxNetManagerCallback)callback { + NSMutableDictionary *mdic = [NSMutableDictionary new]; + [mdic setObject:[LuxNetManager appId] forKey:@"appid" ]; + [mdic setObject:[LuxNetManager getIdfa] forKey:@"idfa"]; + [mdic setObject:ecpm?ecpm:@(0) forKey:@"ecpm"]; + [mdic setObject:@(ad) forKey:@"ad"]; + [mdic setObject:adId forKey:@"id"]; + [LuxNetManager uploadData:mdic urlPath:kLocalUrlStr(@"adtask/show") callback:^(NSError * _Nonnull err, BOOL state, NSDictionary * _Nonnull result) { + NSString *status = result[@"status"]; + NSInteger time = [result[@"close"] integerValue]; + if ([status isEqualToString:@"Success"] && ad) { + [LuxADVCControl removeADVCByDelayTime:time]; + } + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_ActionInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"showAd,已上传展示AD操作,%@秒后关闭",@(time/1000)]}]; + if (ad) { + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"AdID:%@,广告开始展示,展示时长%@ms",adId,@(time)]}]; + } + + }]; +} + ++ (void)closeAd:(NSString *)idfa + adId:(NSString *)adId + callback:(LuxNetManagerCallback)callback { + NSMutableDictionary *mdic = [NSMutableDictionary new]; + [mdic setObject:[LuxNetManager appId] forKey:@"appid" ]; + [mdic setObject:[LuxNetManager getIdfa] forKey:@"idfa"]; + [mdic setObject:adId forKey:@"id"]; + [LuxNetManager uploadData:mdic urlPath:kLocalUrlStr(@"adtask/closed") callback:^(NSError * _Nonnull err, BOOL state, NSDictionary * _Nonnull result) { + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_ActionInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"closeAd,已上传关闭AD操作."]}]; + }]; + + [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"AdID:%@,广告已关闭",adId]}]; +} + + ++ (NSString *)appId { + return [NSBundle mainBundle].bundleIdentifier; +} + ++ (NSString *)getIdfa { + if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) { + NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString]; + return idfa; + } else { + return @""; + } +} + +@end