您可通过使用 Audience Network,借助 Facebook 广告让 iOS 应用实现变现。插屏广告是可以在应用中显示的一种全屏广告。要投放这类广告单元,请参阅本指南。或者,如果您对其他类型的广告单元感兴趣,请参见可用的广告单元类型列表。
现在,我们来实现以下插屏广告版位。
FBAudienceNetwork
,声明 ViewController
执行 FBInterstitialAdDelegate
协议,并添加插屏广告单元的实例变量
import UIKit
import FBAudienceNetwork
class ViewController: UIViewController, FBInterstitialAdDelegate {
private var interstitialAd: FBInterstitialAd?
}
viewDidLoad
方法中实例化广告对象,并执行 interstitialAdDidLoad
override func viewDidLoad() {
super.viewDidLoad()
// Instantiate an InterstitialAd object.
// NOTE: the placement ID will eventually identify this as your app. You can ignore it while you are testing
// and replace it later when you have signed up.
// While you are using this temporary code you will only get test ads and if you release
// your code like this to the App Store your users will not receive ads (you will get a 'No Fill' error).
let interstitialAd = FBInterstitialAd(placementID: "YOUR_PLACEMENT_ID")
interstitialAd.delegate = self
// For auto play video ads, it's recommended to load the ad at least 30 seconds before it is shown
interstitialAd.load()
self.interstitialAd = interstitialAd
}
func interstitialAdDidLoad(_ interstitialAd: FBInterstitialAd) {
guard interstitialAd.isAdValid else {
return
}
print("Ad is loaded and ready to be displayed")
interstitialAd.show(fromRootViewController: self)
}
YOUR_PLACEMENT_ID
中显示的编号为临时编号,仅供测试使用。
若您在实时代码中使用此临时编号,您的用户便不会收到广告(他们会收到未填充错误)。您必须在测试之后返回此处,将临时编号换成实时版位编号。
若想了解如何生成实时版位编号,请参阅 Audience Network 设置
选择设备作为构建目标并运行上述代码后,您应该会看到如下结果:在模拟器中投放广告时,应将设置更改为测试模式,以查看测试广告。详情请参阅如何使用测试模式。
屏幕上显示广告时,请勿为 FBInterstitialAd 调用 loadAd
。如需加载另一个 FBInterstitialAd 以供后续使用,可在用户关闭当前这个(例如在 interstitialAdDidClose
回调中执行)之后再操作。
您可以添加以下任意函数,用于处理广告显示、用户点击或关闭广告的情况
func interstitialAdWillLogImpression(_ interstitialAd: FBInterstitialAd) {
print("The user sees the ad")
// Use this function as indication for a user's impression on the ad.
}
func interstitialAdDidClick(_ interstitialAd: FBInterstitialAd) {
print("The user clicked on the ad and will be taken to its destination")
// Use this function as indication for a user's click on the ad.
}
func interstitialAdWillClose(_ interstitialAd: FBInterstitialAd) {
print("The user clicked on the close button, the ad is just about to close")
// Consider to add code here to resume your app's flow
}
func interstitialAdDidClose(_ interstitialAd: FBInterstitialAd) {
print("The user clicked on the close button, the ad is just about to close")
// Consider to add code here to resume your app's flow
}
在视图控制器实施文件中添加并实现以下函数,以处理广告加载失败问题
func interstitialAd(_ interstitialAd: FBInterstitialAd, didFailWithError error: Error) {
print("Interstitial ad failed to load with error: \(error.localizedDescription)")
}
无广告展示时,将调用 interstitialAd:didFailWithError:
,其中 error.code
会设置为 1001
。如果您使用自己的自定义报告或中介层,则可能需要检查代码值并检测这一情况。在这种情况下,您可回退至另一个广告网络,但不能立即重新请求广告。