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 供日後使用,在用戶關閉目前的 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
。如果您使用自己的自訂分析報告或中介服務層,可以檢查錯誤代碼值,並偵測此狀況。您可在發生此狀況時以其他廣告聯播網作為後援,但請勿隨後立即重新要求廣告。