【经验】uniapp接入激励广告代码

397 阅读1分钟

一、广告组件

<template>
	<view  class="fiil-width">
		<slot></slot>
	</view>
</template>

<script>
	export default {
		name: 'StartAdvert',
		data() {
			return {
				ad: null,
				adUnitId: ''
			}
		},
		methods: {
			/**
			 * 获取广告id
			 */
			getAdUniId() {
				const adverts = uni.getStorageSync('adverts')
				// 筛选出激励广告,即type=4
				const jiliAdverts = adverts.filter(item => item.type == 4)
				if (jiliAdverts.length > 0) {
					// 随机从广告里面获取一个广告ID
					let len = this.getRndInteger(0, jiliAdverts.length - 1)
					this.adUnitId = jiliAdverts[len].adpositionId
				} else {
					uni.showToast({
						title: '广告加载失败',
						icon: "none"
					}, 2000)
					setTimeout(() => {
						// this.$emit('playSuccess');
					}, 2000)
				}
			},
			/**
			 * 点击播放广告
			 * */
			playAdvert() {
				uni.showLoading({
					title: '加载中'
				})
				const _this = this
				this.getAdUniId()
				
				// 创建实例
				this.ad = uni.createRewardedVideoAd({
					adpid: _this.adUnitId,
					adUnitId: _this.adUnitId
				});

				this.ad.onLoad(() => {
					uni.hideLoading()
					console.log('拉取广告成功');
				})
				this.ad.onError(err => {
					console.log(err, '拉取广告失败');
					uni.showToast({
						title: '广告加载失败',
						icon: "none"
					}, 2000)
					setTimeout(() => {
						// _this.$emit('playSuccess');
					}, 2000)
				})
				this.ad.show().catch(() => {
					// 失败重试
					_this.ad.load()
						.then(() => _this.ad.show())
						.catch(err => {
							console.log(err, '手动拉取广告失败')
						})
				})

				// 避免奖励重复发放
				try {
					if (this.ad.closeHandler) {
						this.ad.offClose(this.ad.closeHandler);
						console.log("offClose卸载成功");
					}
				} catch (e) {
					console.log("offClose卸载失败");
					console.error(e);
				}
				this.ad.closeHandler = function(res) {
					if (res && res.isEnded || res === undefined) {
						// _this.$emit('playSuccess')
						// 触发父组件页面跳转(最好不要组件套组件)
						_this.$parent.goTo()
						// _this.$emit("goTo")
					} else {
						uni.hideLoading()
						console.log('中途退出');
					}
				};
				this.ad.onClose(this.ad.closeHandler);
			},
			/**
			 * 获取随机数
			 */
			getRndInteger(min, max) {
				return Math.floor(Math.random() * (max - min + 1)) + min
			}
		}
	}
</script>


二、广告的调用

<view @click="judgement">
<start-advert ref="child">
<image class="btn" :src="env+'/static/ytImg/animals/img-btn.png'" mode="" image>
</start-advert>
</view>
//触发广告
judgement() {
this.$refs.child.playAdvert()
},
//广告完成后进程页面跳转
goTo() {
uni.navigateTo({
url: "/pages/animals/birthAninmalsImg/birthAninmalsImg",
});
}