SwiftUI接入穿山甲开屏广告

研究了一下SwiftUI怎么接入穿山甲。

基于穿山甲sdk版本 4.7.0.8 例子地址

1. 首先要先注册一个账号,穿山甲地址
  1. 在广告变现->流量->应用中创建一个应用并记录下应用ID。在这里插入图片描述

  2. 在广告变现->流量->代码位创建一个代码位并记录下代码位ID。注意要把是否应用于GroMore选择成否,要不然就需要用GreMore引擎在这里插入图片描述

  3. 记录账号ID。在这里插入图片描述

2. 安排广告显示位置
import SwiftUI

@main
struct DemoApp: App {
    // 控制广告是否显示
    @State var showAd: Bool = true
    
    var body: some Scene {
        WindowGroup {
            if showAd == true {
                DSplashView(showAd: $showAd)
            } else {
                ContentView()
            }
        }
    }
}

// 获取根rootViewController
extension UIApplication {
  var currentKeyWindow: UIWindow? {
    UIApplication.shared.connectedScenes
      .filter { $0.activationState == .foregroundActive }
      .map { $0 as? UIWindowScene }
      .compactMap { $0 }
      .first?.windows
      .filter { $0.isKeyWindow }
      .first
  }

  var rootViewController: UIViewController? {
    currentKeyWindow?.rootViewController
  }
}

2.广告初始化,由于高版本的直接使用switf初始化有点问题,改成包了一个OC

DAdHandler.h

#ifndef DAdHandler_h
#define DAdHandler_h

#import <Foundation/Foundation.h>

@interface DAdHandler : NSObject

- (instancetype)init;

@end

#endif /* Header_h */

DAdHandler.m

#import <Foundation/Foundation.h>
#import "DAdHandler.h"
#import <BUAdSDK/BUAdSDKManager.h>
#import <BUAdSDK/BUAdSDKConfiguration.h>

@interface DAdHandler()

@end

@implementation DAdHandler

- (instancetype)init {
    if (self = [super init]) {
        [self initADSdk];
    }
    return self;
}

- (void)initADSdk {
    BUAdSDKConfiguration* config = [BUAdSDKConfiguration alloc];
    [config setAppID:@"5328067"];
    
    NSLog(@"DAdHandler init");
    
    [BUAdSDKManager startWithSyncCompletionHandler:^(BOOL success, NSError *error) {
        if (success) {
            NSLog(@"初始化成功");
        } else {
            NSLog(@"初始化失败");
        }
    }];
}

@end
3. 广告界面
//
//  DSplashView.swift
//  Demo
//
//  Created by wangyu on 2022/8/25.
//

import SwiftUI
import BUAdSDK
import AdSupport
import AppTrackingTransparency

class DSplashInstance: NSObject, BUSplashAdDelegate {
    var delegate: DSplashInstanceProtocol?
    
    lazy var splashAdInstance: BUSplashAd? = {
        let instance = BUSplashAd.init(slotID: "887901739", adSize: .init(width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))
        return instance
    }()
    
     override init() {
         super.init()
        
         // 延时一会执行,要不然可能拿不到广告IDFA
         DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [self] in
             if #available(iOS 14.0, *) {
                 ATTrackingManager.requestTrackingAuthorization { [self] status in
                     print("请求idfa状态 \(status)")
                     if status == .authorized {
                         DAdHandler.init()
                         print("idfa \(ASIdentifierManager.shared().advertisingIdentifier)")
                         
                         

                         if self.splashAdInstance != nil {
                             print("初始化广告位成功")
                         }

                         self.splashAdInstance?.delegate = self
                         self.splashAdInstance?.loadData()
                     }
                 }
             } else {
                 DAdHandler.init()

                 if self.splashAdInstance != nil {
                     print("初始化广告位成功")
                 }

                 self.splashAdInstance?.delegate = self
                 self.splashAdInstance?.loadData()
             }
         }
    }
    
    func splashAdLoadSuccess(_ splashAd: BUSplashAd) {
        print("广告加载成功")
    }
    
    func splashAdLoadFail(_ splashAd: BUSplashAd, error: BUAdError?) {
        print("广告加载失败 \(error?.userInfo)")
    }
    
    func splashAdRenderSuccess(_ splashAd: BUSplashAd) {
        print("广告加载渲染成功")
        if UIApplication.shared.rootViewController != nil {
            splashAd.showSplashView(inRootViewController: UIApplication.shared.rootViewController!)
        }
    }
    
    func splashAdRenderFail(_ splashAd: BUSplashAd, error: BUAdError?) {
        print("广告加载渲染失败")
    }
    
    func splashAdWillShow(_ splashAd: BUSplashAd) {
        print("广告将要显示")
    }
    
    func splashAdDidShow(_ splashAd: BUSplashAd) {
        print("广告已经显示")
    }
    
    func splashAdViewControllerDidClose(_ splashAd: BUSplashAd) {
        print("广告关闭")
        delegate?.closeAd()
    }
    
    func splashDidCloseOtherController(_ splashAd: BUSplashAd, interactionType: BUInteractionType) {
        print("广告关闭其他")
    }
    
    func splashVideoAdDidPlayFinish(_ splashAd: BUSplashAd, didFailWithError error: Error) {
        print("广告播放完成")
    }
    
    func splashAdDidClick(_ splashAd: BUSplashAd) {
        print("广告点击")
    }
    
    func splashAdDidClose(_ splashAd: BUSplashAd, closeType: BUSplashAdCloseType) {
        print("广告关闭")
    }
}

protocol DSplashInstanceProtocol {
    func closeAd()
}

struct DSplashView: View, DSplashInstanceProtocol {
    @Binding var showAd: Bool
    private var adInstanse: DSplashInstance?
    
    init(showAd: Binding<Bool>) {
        self._showAd = showAd
        adInstanse = DSplashInstance()
        adInstanse?.delegate = self
    }
    
    func closeAd() {
        showAd = false
    }
    
    var body: some View {
        VStack {
            Color.gray
        }
    }
}

struct DSplashView_Previews: PreviewProvider {
    @State static var showAd: Bool = true
    
    static var previews: some View {
        DSplashView(showAd: $showAd)
    }
}

5. 测试的话,需要用到的增加测试工具项

在这里插入图片描述
IDFA如果同意的话,在日志中就能看到了。

例子地址

### 关于 UniApp 框架的推荐资源与教程 #### 1. **Uniapp 官方文档** 官方文档是最权威的学习资料之一,涵盖了从基础概念到高级特性的全方位讲解。对于初学者来说,这是了解 UniApp 架构和技术细节的最佳起点[^3]。 #### 2. **《Uniapp 从入门到精通:案例分析与最佳实践》** 该文章提供了系统的知识体系,帮助开发者掌握 Uniapp 的基础知识、实际应用以及开发过程中的最佳实践方法。它不仅适合新手快速上手,也能够为有经验的开发者提供深入的技术指导[^1]。 #### 3. **ThorUI-uniapp 开源项目教程** 这是一个专注于 UI 组件库设计和实现的教学材料,基于 ThorUI 提供了一系列实用的功能模块。通过学习此开源项目的具体实现方式,可以更好地理解如何高效构建美观且一致的应用界面[^2]。 #### 4. **跨平台开发利器:UniApp 全面解析与实践指南** 这篇文章按照章节形式详细阐述了 UniApp 的各个方面,包括但不限于其工作原理、技术栈介绍、开发环境配置等内容,并附带丰富的实例演示来辅助说明理论知识点。 以下是几个重要的主题摘选: - **核心特性解析**:解释了跨端运行机制、底层架构组成及其主要功能特点。 - **开发实践指南**:给出了具体的页面编写样例代码,展示了不同设备间 API 调用的方法论。 - **性能优化建议**:针对启动时间缩短、图形绘制效率提升等方面提出了可行策略。 ```javascript // 示例代码片段展示条件编译语法 export default { methods: { showPlatform() { console.log(process.env.UNI_PLATFORM); // 输出当前平台名称 #ifdef APP-PLUS console.log('Running on App'); #endif #ifdef H5 console.log('Running on Web'); #endif } } } ``` #### 5. **其他补充资源** 除了上述提到的内容外,还有许多在线课程视频可供选择,比如 Bilibili 上的一些免费系列讲座;另外 GitHub 和 GitCode 平台上也有不少优质的社区贡献作品值得借鉴研究。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xyccstudio

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值