728x90
반응형
이전 포스팅에 간단하게 광고를 설정하는 방법을 적어놨으니 확인바랍니다.
final class Interstitial: NSObject, GADFullScreenContentDelegate {
let adUnitID = "ca-app-pub-6235545617614297/1320470587"
private var interstitial: GADInterstitialAd?
override init() {
super.init()
loadInterstitial()
}
func loadInterstitial(){
let request = GADRequest()
GADInterstitialAd.load(withAdUnitID:adUnitID,
request: request,
completionHandler: { [self] ad, error in
if let error = error {
print("Failed to load interstitial ad: \(error.localizedDescription)")
return
}
interstitial = ad
interstitial?.fullScreenContentDelegate = self
}
)
}
/// Tells the delegate that the ad failed to present full screen content.
func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
print("Ad did fail to present full screen content.")
}
/// Tells the delegate that the ad dismissed full screen content.
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
print("Ad did dismiss full screen content.")
loadInterstitial()
}
func showAd(){
let root = UIApplication.shared.windows.first?.rootViewController
interstitial?.present(fromRootViewController: root!)
}
}
내 경우에는 Extension이나 Manager 같은 폴더를 하나 만들고 그 안에 GoogleAdManager.swift 파일을 만들어 전체적인 광고모듈을 넣어놓고 관리한다.
위 코드도 별도의 swift파일을 생성해서 만들어놓으면 추후에 관리하기 편할 것이다.
그 후에 View단에서 가져다 쓰기만 하면 된다.
struct ContentView: View {
let interstitial = Interstitial()
var body: some View {
Button {
interstitial.showAd()
}, label: {
Text("Show Ad")
}
}
}728x90
반응형
'iOS' 카테고리의 다른 글
| Xcode 설치 방법 (0) | 2023.03.14 |
|---|---|
| Swift에서 QR Code 이미지 생성하는 법 (0) | 2023.02.26 |
| UIImage에서 만든 MTLTexture의 orientation이 이상할 때 (0) | 2023.02.25 |
| [SwiftUI] Google AdMob 적용하기 (배너광고, 보상형광고) (0) | 2022.08.16 |
| [SwiftUI] View에 테두리(customBorder)를 추가하는 방법 (0) | 2022.08.16 |