SwiftyAds 开源项目使用教程
1. 项目的目录结构及介绍
SwiftyAds 是一个用于在 Swift 项目中展示 Google AdMob 广告的库。以下是项目的目录结构及其介绍:
swifty-ads/
├── Sources/
│ ├── SwiftyAds/
│ │ ├── Models/
│ │ ├── Services/
│ │ ├── SwiftyAds.swift
│ │ ├── SwiftyAdsError.swift
│ │ └── ...
│ └── SwiftyAdsDemo/
│ ├── AppDelegate.swift
│ ├── SceneDelegate.swift
│ ├── ViewControllers/
│ └── ...
├── Tests/
│ └── SwiftyAdsTests/
├── .gitignore
├── .swiftpm
├── LICENSE
├── README.md
└── Package.swift
- Sources/SwiftyAds/: 包含 SwiftyAds 库的核心代码,包括模型、服务和主要功能文件。
- Sources/SwiftyAdsDemo/: 包含示例应用程序的代码,用于演示如何使用 SwiftyAds 库。
- Tests/SwiftyAdsTests/: 包含单元测试代码,用于测试 SwiftyAds 库的功能。
- .gitignore: 指定 Git 版本控制系统忽略的文件和目录。
- .swiftpm: Swift 包管理器的配置文件。
- LICENSE: 项目的许可证文件。
- README.md: 项目的说明文档。
- Package.swift: Swift 包管理器的描述文件。
2. 项目的启动文件介绍
在 SwiftyAdsDemo 示例应用程序中,主要的启动文件是 AppDelegate.swift
和 SceneDelegate.swift
。
AppDelegate.swift
AppDelegate.swift
是应用程序的入口点,负责处理应用程序的生命周期事件。以下是示例代码:
import UIKit
import SwiftyAds
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// 配置 SwiftyAds
SwiftyAds.shared.configure(
environment: .production,
adUnitIdForBanner: "your-banner-ad-unit-id",
adUnitIdForInterstitial: "your-interstitial-ad-unit-id",
adUnitIdForRewarded: "your-rewarded-ad-unit-id",
adUnitIdForRewardedInterstitial: "your-rewarded-interstitial-ad-unit-id",
request: .default,
consentStatus: .notRequired,
consentConfiguration: .default,
mediationConfig: nil,
showTargetingAds: true
)
return true
}
}
SceneDelegate.swift
SceneDelegate.swift
是 iOS 13 及以上版本中处理应用程序场景(Scene)生命周期的文件。以下是示例代码:
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let _ = (scene as? UIWindowScene) else { return }
}
}
3. 项目的配置文件介绍
SwiftyAds 的配置主要在 SwiftyAds.swift
文件中进行。以下是配置文件的介绍:
SwiftyAds.swift
SwiftyAds.swift
文件包含了 SwiftyAds 的主要配置和功能实现。以下是部分代码示例:
import GoogleMobileAds
public class SwiftyAds: NSObject {
public static let shared = SwiftyAds()
private override init() {}
public func configure(
environment: Environment,
adUnitIdForBanner: String,
adUnitIdForInterstitial: String,
adUnitIdForRewarded: String,
adUnitIdForRewardedInterstitial: String,
request: GADRequest,
consentStatus: ConsentStatus,
consentConfiguration: ConsentConfiguration,
mediationConfig: MediationConfig?,
showTargetingAds: Bool