iOS 横幅广告集成
概述
横幅广告是一种在应用界面顶部或底部显示的长方形广告,具有以下特点:
- 占用空间小,不影响用户体验
- 持续展示,提高广告曝光率
- 加载速度快,响应迅速
- 适合在各种应用场景中使用
横幅广告需通过容器视图(container: UIView)承载展示。
集成步骤
1. 创建并加载横幅广告
swift
import UIKit
import UjuAdCore
final class BannerAdHelper {
private var bannerAd: UjuAdObject?
func load(vc: UIViewController) {
// 创建广告配置,指定广告位 ID 与广告尺寸
let config = UjuAdConfig(
placementId: "YOUR_BANNER_PLACEMENT_ID",
adViewSize: AdViewSize.bannerSize320x50 // 320x50
)
let banner = UjuAdObject.getBannerObject(vc, config: config)
banner.setAdObjectListener(BannerListener(helper: self))
self.bannerAd = banner
banner.load()
}
func show(vc: UIViewController, container: UIView) {
// 展示前判断 isReady,需传入承载横幅的容器视图
if bannerAd?.isReady() == true {
bannerAd?.show(vc, container: container)
}
}
func destroy() {
bannerAd?.destroy()
bannerAd = nil
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2. 实现横幅监听器
swift
final class BannerListener: FeedAdObjectListener, @unchecked Sendable {
private weak var helper: BannerAdHelper?
init(helper: BannerAdHelper) { self.helper = helper }
func onLoadSuccess() {
// 加载成功,可在合适时机调用 show(vc, container:)
}
func onLoadError(error: UjuException) {
print("横幅加载失败: \(error.description)")
}
func onAdShow() {
// 通过 getAdInfo() 获取广告信息,读取 ecpm
// let ecpm = helper?.bannerAd?.getAdInfo()?.ecpm
}
func onAdClicked() {
// 广告被点击
}
func onAdClosed() {
// 广告关闭
}
func onLpClosed() {
// 落地页关闭
}
func onAdError(error: UjuException) {
print("横幅展示错误: \(error.description)")
}
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
UjuAdConfig 配置说明
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
placementId | String | 是 | 广告位 ID |
adViewSize | AdViewSize? | 否 | 广告尺寸,仅对模板渲染生效,默认 nil |
scenarioKey | String? | 否 | 广告展示场景标识,用于统计 |
userId | String? | 否 | 用户 ID |
customData | [String: String]? | 否 | 自定义数据,透传给广告服务端 |
bidFloor | Double | 否 | 底价(元,CPM),由第三方聚合平台集成时传入,普通集成方无需设置 |
广告尺寸
优聚智汇 iOS SDK 提供以下预设横幅尺寸(AdViewSize 静态属性,单位为像素):
| 预设属性 | 宽 × 高 | 描述 |
|---|---|---|
AdViewSize.bannerSize320x50 | 320 × 50 | 标准横幅(推荐) |
AdViewSize.bannerSize320x100 | 320 × 100 | 大型横幅 |
AdViewSize.bannerSize320x75 | 320 × 75 | 智能横幅 |
如需自定义尺寸,可直接构造:
swift
let customSize = AdViewSize(width: 300, height: 250)1
完整
AdViewSize预设(含 Native 尺寸)参见 API 参考。
最佳实践
1. 广告位置
- 底部放置:最常见的位置,不遮挡主要内容
- 顶部放置:适合某些特定应用场景
- 内容之间:在长文章或列表中穿插
2. 优化建议
- 预加载广告:在需要展示广告前提前加载
- 处理网络状态:在网络差时适当调整加载策略
- 测试不同尺寸:根据应用界面选择合适的广告尺寸
3. 避免的问题
- 不要在同一屏幕放置多个横幅广告
- 不要遮挡应用的核心功能
- 不要在用户交互频繁的区域放置广告
常见问题
Q: 横幅广告为什么不显示?
A: 可能的原因:
- 广告位 ID 不正确
- 网络连接问题
- 广告库存不足(错误码 102
noFill) - 容器视图不可见或尺寸为 0
- 未在
onLoadSuccess后调用show(vc, container:)
Q: 横幅广告可以在 UITableView/UICollectionView 中使用吗?
A: 可以,但需要注意:
- 在 cell 中管理广告视图生命周期
- 正确处理广告对象的
destroy(),避免内存泄漏 - 避免频繁创建和销毁广告视图
