Wallpaper_Home/wallpaper_project/Main/WA_limitsVCViewController.swift
2024-08-19 14:40:12 +08:00

398 lines
14 KiB
Swift
Raw Permalink 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.

//
// WA_limitsVCViewController.swift
// wallpaper_project
import UIKit
import SVProgressHUD
import Photos
import Alamofire
import AppLovinSDK
import FirebaseAnalytics
import FirebaseRemoteConfig
import MTGSDKNewInterstitial
import MTGSDKBidding
import MTGSDK
import AnyThinkInterstitial
class WA_limitsVCViewController: WA_RootVC {
@IBOutlet weak var retryBtn: UIButton!
let activityView = UIActivityIndicatorView()
@IBOutlet weak var resourceLabel: UILabel!
var interstitialAd: MAInterstitialAd!
var retryAttempt = 0.0
var adCheckTimer: Timer?
var adCheckStartTime: Date?
var adLoadTime: Int = 0
var idad:String?
var remoteConfig: RemoteConfig!
var failureCount = 0
private var retryTimer: Timer?
private var retryAttempts = 0
private let maxRetryAttempts = 3
private let retryInterval: TimeInterval = 3
// var ivAadManager:MTGNewInterstitialAdManager!
var bidToken:String?
var ecpmprice:Double?
var newInterstitialAdManager:MTGNewInterstitialBidAdManager?
var idstring:String = "n66bdc1e78a5d9"
override func viewDidLoad() {
super.viewDidLoad()
requestPhotoLibraryPermission()
// Remote Config
remoteConfig = RemoteConfig.remoteConfig()
self.idstring = getRandomString() ?? "n66bdc1e78a5d9"
//
let settings = RemoteConfigSettings()
settings.minimumFetchInterval = 0
remoteConfig.configSettings = settings
// Fetch
remoteConfig.setDefaults(fromPlist: "isopen")
self.resourceLabel.isHidden = false
activityView.center = CGPoint(x: self.view.center.x + 10, y: self.view.bounds.size.height - 100 )
//
activityView.hidesWhenStopped = true
activityView.color = .black;
activityView.style = UIActivityIndicatorView.Style.whiteLarge
self.view.addSubview(activityView)
self.activityView.startAnimating()
DispatchQueue.main.asyncAfter(wallDeadline: .now() + 3) {
self.loadTopAD()
}
}
func loadTopAD(){
let extra: [String: Any] = [
kATAdLoadingExtraMediaExtraKey: "custom_values"
]
ATAdManager.shared().loadAD(withPlacementID: self.idstring, extra: extra, delegate: self)
self.fetchRemoteConfig()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.retryBtn.isHidden = true
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
//
requestTrackingAuthorization { idfa in
if let idfa = idfa {
print("IDFA: \(idfa)")
StartManager.shared.idfaid = idfa
print("Stored IDFA: \(StartManager.shared.idfaid ?? "N/A")")
} else {
print("IDFA is not available or tracking authorization denied.")
}
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
//
requestTrackingAuthorization { idfa in
if let idfa = idfa {
print("IDFA: \(idfa)")
StartManager.shared.idfaid = idfa
print("Stored IDFA: \(StartManager.shared.idfaid ?? "N/A")")
} else {
print("IDFA is not available or tracking authorization denied.")
}
}
}
}
func fetchRemoteConfig() {
let localVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0.0"
print("version ------- \(localVersion)")
remoteConfig.fetch { [weak self] (status, error) in
guard let self = self else { return }
if status == .success {
self.retryAttempts = 0
print("Config fetched!")
self.remoteConfig.activate { changed, error in
if error == nil {
let js = self.remoteConfig.configValue(forKey: "isopen").jsonValue as! [String: Any]
let valueopen = js["isadopen"] as! Bool
let valueversion = js["version"] as! String
let tt = UserDefaults.standard
print("-------\(tt.bool(forKey: "iswindows"))")
DispatchQueue.main.async {
if valueversion == localVersion {
let userDefaults = UserDefaults.standard
if userDefaults.bool(forKey: "iswindows"){
let appDelegate = UIApplication.shared.delegate
appDelegate?.window??.rootViewController = WA_RootNAV(rootViewController: WA_playerVC())
}else{
WA_TabbarCommon.TabBarController()
}
StartManager.shared.superHero = false
} else {
if valueopen {
// self.newInterstitialAdManager?.loadAd(withBidToken:self.bidToken!)
self.startAdCheck()
StartManager.shared.superHero = true
} else {
let userDefaults = UserDefaults.standard
if userDefaults.bool(forKey: "iswindows"){
let appDelegate = UIApplication.shared.delegate
appDelegate?.window??.rootViewController = WA_RootNAV(rootViewController: WA_playerVC())
}else{
WA_TabbarCommon.TabBarController()
}
StartManager.shared.superHero = false
}
}
}
}
}
} else {
print("Config not fetched")
if let error = error {
print("Error: \(error.localizedDescription)")
}
self.retryAttempts += 1
if self.retryAttempts <= self.maxRetryAttempts {
//
self.retryTimer?.invalidate()
//
self.retryTimer = Timer.scheduledTimer(withTimeInterval: self.retryInterval, repeats: false) { [weak self] _ in
self?.fetchRemoteConfig()
}
} else {
print("Max retry attempts reached. Stopping retries.")
let userDefaults = UserDefaults.standard
if userDefaults.bool(forKey: "iswindows"){
let appDelegate = UIApplication.shared.delegate
appDelegate?.window??.rootViewController = WA_RootNAV(rootViewController: WA_playerVC())
}else{
WA_TabbarCommon.TabBarController()
}
}
}
}
}
// /
func startAdCheck() {
// createInterstitialAd()
// newInterstitialAdManager?.loadAd(withBidToken:self.bidToken!)
adCheckStartTime = Date()
adCheckTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(checkAdStatus), userInfo: nil, repeats: true)
}
@objc func checkAdStatus() {
let elapsedTime = Date().timeIntervalSince(adCheckStartTime!)
let elapsedTimeInMilliseconds = Int(elapsedTime * 1000)
// self.newInterstitialAdManager?.loadAd(withBidToken:self.bidToken!)
// let issureready = newInterstitialAdManager!.isAdReady()
if ATAdManager.shared().interstitialReady(forPlacementID: self.idstring)
{
ATAdManager.shared().showInterstitial(withPlacementID: self.idstring, in: self, delegate: self)
adLoadTime = elapsedTimeInMilliseconds //
adCheckTimer?.invalidate()
self.activityView.stopAnimating()
if StartManager.shared.idfaid == ""{
self.fetchIDFAUntilSuccess()
}else{
setPostSHOW()
StartManager.shared.shelfNumber = "开屏show"
}
}else if elapsedTimeInMilliseconds >= 10000{
adCheckTimer?.invalidate()
let userDefaults = UserDefaults.standard
if userDefaults.bool(forKey: "iswindows"){
let appDelegate = UIApplication.shared.delegate
appDelegate?.window??.rootViewController = WA_RootNAV(rootViewController: WA_playerVC())
}else{
WA_TabbarCommon.TabBarController()
}
Analytics.logEvent("open_load_fail", parameters: nil)
self.activityView.stopAnimating()
}else{
print("广告未准备好,继续检查...")
}
}
///
func requestPhotoLibraryPermission() {
//
let status = PHPhotoLibrary.authorizationStatus()
//
switch status {
case .authorized:
// 访
print("相册权限已授权")
case .denied, .restricted:
// 访
print("相册权限已拒绝或受限,请在设置中开启权限")
case .notDetermined:
//
PHPhotoLibrary.requestAuthorization { [weak self] (newStatus) in
DispatchQueue.main.async {
if newStatus == .authorized {
// 访
print("用户已授权访问相册")
} else {
// 访
print("用户未授权访问相册")
}
}
}
@unknown default:
//
print("未知的相册权限状态")
}
}
func fetchIDFAUntilSuccess() {
DispatchQueue.global(qos: .background).async {
var idfaObtained = false
while !idfaObtained {
let semaphore = DispatchSemaphore(value: 0)
requestIDFA { idfa in
if let idfa = idfa {
print("Got IDFA: \(idfa)")
// IDFA
// self.performActionWithIDFA(idfa)
StartManager.shared.idfaid = idfa
// self.setPostSHOW()
idfaObtained = true
} else {
print("Failed to get IDFA, retrying...")
DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + 1.0) {
semaphore.signal()
}
}
}
semaphore.wait()
}
}
}
}
extension WA_limitsVCViewController:ATInterstitialDelegate{
func didFinishLoadingAD(withPlacementID placementID: String!) {
print("----")
}
// 广
func interstitialDidShow(forPlacementID placementID: String, extra: [AnyHashable : Any]) {
print("----成功")
}
/// 广
func interstitialDidClick(forPlacementID placementID: String, extra: [AnyHashable : Any]) {
print("----点击")
}
// 广
func interstitialDidClose(forPlacementID placementID: String, extra: [AnyHashable : Any]) {
print("----关闭")
WA_TabbarCommon.TabBarController()
}
// 广
func didFinishLoadingADSource(withPlacementID placementID: String!,extra: [AnyHashable : Any]?) {
let networkID = extra?["network_firm_id"]
let ecpm = extra?["adsource_price"]
let country = extra?["country"]
if let adsourcePriceString = extra?["adsource_price"] as? String,
let adsourcePrice = Double(adsourcePriceString) {
StartManager.shared.ecpm = Float(adsourcePrice) / 1000
print("-----ecpm ID: \(StartManager.shared.ecpm)")
} else {
print("无法获取 adsource_price 或类型不匹配")
}
StartManager.shared.countryCode = country as? String
StartManager.shared.network = network(networkID as! Int)
StartManager.shared.shelfNumber = "开屏load"
StartManager.shared.adId = self.idstring
setPostload()
print("ATInterstitialViewController::didFailToLoadADWithPlacementID:\(placementID)")
}
// load
func didFailToLoadAD(withPlacementID placementID: String!, error: (any Error)!) {
print("----load失败")
print("ATInterstitialViewController::didFailToLoadADWithPlacementID:\(String(describing: placementID))---error\(String(describing: error))")
}
}