iOS: banners, native ads, impression data and the 0.3.0 methods

Pass-through overlay inside the WebView (hitTest returns nil outside ad views), banners with presets,
ADAPTIVE (recreated on safe-area width changes), CUSTOM sizes, top / bottom / center with offsets and
safe area, small and medium native templates built in code (ISNativeAdView binding, colours, corner
radius, system or web-asset fonts), per-ad impression delegates with a queue of 100 flushed on the
first impressionData listener (native impressions synthesised, conversionValue included),
adInfoChanged, getCapabilities, setSegment, setDynamicUserId, isPlacementCapped, getReward, and
cleanup on plugin deinit.
This commit is contained in:
CRTkafa 2026-10-10 05:29:00 +08:00
parent 18a8d7c7a1
commit c6dd670f34
9 changed files with 1576 additions and 14 deletions

View file

@ -0,0 +1,334 @@
import IronSource
import UIKit
protocol AdHost: AnyObject {
func hostViewController() -> UIViewController?
/// The overlay, attached on first use; nil when there is no WebView.
func overlay() -> OverlayHost?
var initialized: Bool { get }
func emit(_ event: String, _ data: [String: Any])
}
/// Banners (design §3, §6): `LPMBannerAdView` instances keyed by bannerId, laid out in the OverlayHost.
/// Main thread only.
final class BannerManager {
/// Owner decision Q4: adaptive banners follow safe-area width changes after the layout settled.
private static let adaptiveRecreateDelay: TimeInterval = 0.25
weak var host: AdHost?
private let impressionDelegate: LPMImpressionDataDelegate
private var slots: [String: Slot] = [:]
private var adaptiveCheck: DispatchWorkItem?
init(impressionDelegate: LPMImpressionDataDelegate) {
self.impressionDelegate = impressionDelegate
}
final class Slot {
let bannerId: String
let adUnitId: String
let size: String
let fixedAdaptiveWidth: Int?
let customWidth: Int
let customHeight: Int
let placementName: String?
let bidFloor: Double?
var position = "bottom"
var offsetX: CGFloat = 0
var offsetY: CGFloat = 0
var respectSafeArea = true
var view: LPMBannerAdView!
var listener: Listener?
var adSize: LPMAdSize!
/// CSS px width the adaptive size was computed for.
var adaptiveWidthUsed = 0
var visible = false
var loadRequested = false
var frame = CGRect.zero
var loggedFrame = CGRect.null
init(bannerId: String, adUnitId: String, size: String, fixedAdaptiveWidth: Int?, customWidth: Int,
customHeight: Int, placementName: String?, bidFloor: Double?) {
self.bannerId = bannerId
self.adUnitId = adUnitId
self.size = size
self.fixedAdaptiveWidth = fixedAdaptiveWidth
self.customWidth = customWidth
self.customHeight = customHeight
self.placementName = placementName
self.bidFloor = bidFloor
}
}
// MARK: - API
func create(_ o: [String: Any]) throws -> [String: Any] {
guard let adUnitId = Args.nonEmpty(o, "adUnitId") else { throw CallError.invalid("adUnitId is required") }
let bannerId = Args.nonEmpty(o, "bannerId") ?? adUnitId
let custom = Args.object(o, "customSize")
let size = Args.string(o, "size") ?? (custom != nil ? "CUSTOM" : "ADAPTIVE")
if !OverlayMath.isBannerSize(size) { throw CallError.invalid("Unknown banner size '\(size)'") }
var cw = 0, ch = 0
if size == "CUSTOM" {
guard let custom = custom else { throw CallError.invalid("size CUSTOM needs customSize { width, height }") }
cw = try Args.positiveInt(custom, "customSize.width", "width")
ch = try Args.positiveInt(custom, "customSize.height", "height")
}
var fixedWidth: Int?
if Args.present(o, "adaptiveWidth") { fixedWidth = try Args.positiveInt(o, "adaptiveWidth", "adaptiveWidth") }
var bidFloor: Double?
if Args.present(o, "bidFloor") {
guard let v = Args.number(o["bidFloor"]), v >= 0 else { throw CallError.invalid("bidFloor must be a number >= 0") }
bidFloor = v
}
let placement = Args.nonEmpty(o, "placementName")
let s = Slot(bannerId: bannerId, adUnitId: adUnitId, size: size, fixedAdaptiveWidth: fixedWidth, customWidth: cw,
customHeight: ch, placementName: placement, bidFloor: bidFloor)
try applyLayout(s, o)
guard let host = host, host.initialized else {
throw CallError("NOT_INITIALIZED", "Call initialize() and wait for it before createBanner()")
}
if slots[bannerId] != nil { throw CallError("ALREADY_EXISTS", "Banner '\(bannerId)' already exists; destroy it first") }
guard host.hostViewController() != nil else {
throw CallError("NO_VIEW_CONTROLLER", "No view controller to attach the banner to")
}
guard let overlay = host.overlay() else {
throw CallError("NO_VIEW_CONTROLLER", "The WebView is not attached to a view hierarchy")
}
try buildView(s, overlay)
slots[bannerId] = s
relayout(s, overlay)
return result(s)
}
func load(_ bannerId: String?) throws {
let s = try require(bannerId)
guard let vc = host?.hostViewController() else {
throw CallError("NO_VIEW_CONTROLLER", "No view controller to load the banner with")
}
s.loadRequested = true
s.view.loadAd(with: vc)
}
func show(_ bannerId: String?) throws -> [String: Any] {
let s = try require(bannerId)
s.visible = true
s.view.isHidden = false
s.view.superview?.bringSubviewToFront(s.view)
s.view.resumeAutoRefresh()
if let overlay = host?.overlay() {
relayout(s, overlay)
log(s, overlay)
}
return result(s)
}
func hide(_ bannerId: String?) {
guard let id = bannerId, let s = slots[id] else { return }
s.visible = false
s.view.isHidden = true
s.view.pauseAutoRefresh()
levelPlayLog.notice("banner \(s.bannerId, privacy: .public) hidden")
}
func setLayout(_ o: [String: Any]) throws -> [String: Any] {
let s = try require(Args.string(o, "bannerId"))
try applyLayout(s, o)
if let overlay = host?.overlay() { relayout(s, overlay) }
return result(s)
}
func destroy(_ bannerId: String?) {
guard let id = bannerId, let s = slots.removeValue(forKey: id) else { return }
destroyView(s)
}
func destroyAll() {
adaptiveCheck?.cancel()
adaptiveCheck = nil
for s in slots.values { destroyView(s) }
slots.removeAll()
}
/// Overlay layout pass: re-place every banner and schedule the adaptive width check (Q4).
func onLayoutChanged(_ overlay: OverlayHost) {
var adaptiveChanged = false
for s in slots.values {
relayout(s, overlay)
if followsWidth(s) && currentAdaptiveWidth(s, overlay) != s.adaptiveWidthUsed { adaptiveChanged = true }
}
adaptiveCheck?.cancel()
adaptiveCheck = nil
if adaptiveChanged {
let work = DispatchWorkItem { [weak self] in self?.recreateChangedAdaptive() }
adaptiveCheck = work
DispatchQueue.main.asyncAfter(deadline: .now() + Self.adaptiveRecreateDelay, execute: work)
}
}
// MARK: - Internals
private func require(_ bannerId: String?) throws -> Slot {
guard let id = bannerId, !id.isEmpty else { throw CallError.invalid("bannerId is required") }
guard let s = slots[id] else { throw CallError.notFound("Banner", id) }
return s
}
private func applyLayout(_ s: Slot, _ o: [String: Any]) throws {
if Args.present(o, "position") {
guard let p = o["position"] as? String, OverlayMath.isPosition(p) else {
throw CallError.invalid("position must be 'top', 'bottom' or 'center'")
}
s.position = p
}
if Args.present(o, "offsetX") { s.offsetX = CGFloat(try Args.finite(o, "offsetX")) }
if Args.present(o, "offsetY") { s.offsetY = CGFloat(try Args.finite(o, "offsetY")) }
if Args.present(o, "respectSafeArea") {
guard Args.isBool(o["respectSafeArea"]), let b = o["respectSafeArea"] as? Bool else {
throw CallError.invalid("respectSafeArea must be a boolean")
}
s.respectSafeArea = b
}
}
private func followsWidth(_ s: Slot) -> Bool {
return s.size == "ADAPTIVE" && s.fixedAdaptiveWidth == nil
}
private func area(_ s: Slot, _ overlay: OverlayHost) -> CGRect {
return s.respectSafeArea ? overlay.safeAreaCss : overlay.webViewCss
}
private func currentAdaptiveWidth(_ s: Slot, _ overlay: OverlayHost) -> Int {
return Int(area(s, overlay).width.rounded(.down))
}
private func resolveSize(_ s: Slot, _ overlay: OverlayHost) -> LPMAdSize? {
switch s.size {
case "BANNER": return LPMAdSize.banner()
case "LARGE": return LPMAdSize.large()
case "MEDIUM_RECTANGLE": return LPMAdSize.mediumRectangle()
case "LEADERBOARD": return LPMAdSize.leaderBoard()
case "CUSTOM": return LPMAdSize.customSize(withWidth: s.customWidth, height: s.customHeight)
default:
// 1 CSS px = 1 pt; the SDK width is in points.
let width = s.fixedAdaptiveWidth ?? currentAdaptiveWidth(s, overlay)
s.adaptiveWidthUsed = width
return width > 0 ? LPMAdSize.createAdaptiveAdSize(withWidth: CGFloat(width)) : LPMAdSize.createAdaptive()
}
}
private func buildView(_ s: Slot, _ overlay: OverlayHost) throws {
guard let size = resolveSize(s, overlay) else {
throw CallError("NOT_INITIALIZED", "The SDK returned no adaptive size (initialize() not finished)")
}
let builder = LPMBannerAdViewConfigBuilder().set(adSize: size)
if let floor = s.bidFloor { _ = builder.set(bidFloor: NSNumber(value: floor)) }
if let placement = s.placementName { _ = builder.set(placementName: placement) }
let view = LPMBannerAdView(adUnitId: s.adUnitId, config: builder.build())
let listener = Listener(manager: self, slot: s, view: view)
view.setDelegate(listener)
view.setImpressionDataDelegate(impressionDelegate)
view.isHidden = !s.visible
s.view = view
s.listener = listener
s.adSize = size
overlay.add(view)
}
private func relayout(_ s: Slot, _ overlay: OverlayHost) {
s.frame = OverlayMath.bannerFrame(area(s, overlay), width: CGFloat(s.adSize.width), height: CGFloat(s.adSize.height),
position: s.position, offsetX: s.offsetX, offsetY: s.offsetY)
overlay.place(s.view, s.frame)
if s.frame != s.loggedFrame {
s.loggedFrame = s.frame
log(s, overlay)
}
}
private func log(_ s: Slot, _ overlay: OverlayHost) {
levelPlayLog.notice("banner \(s.bannerId, privacy: .public) frame \(Self.describe(s.view.frame), privacy: .public) in \(Self.describe(overlay.bounds), privacy: .public) safe \(Self.describe(overlay.safeAreaCss), privacy: .public) visible \(s.visible, privacy: .public)")
}
static func describe(_ r: CGRect) -> String {
return String(format: "%.1f,%.1f %.1fx%.1f", r.minX, r.minY, r.width, r.height)
}
private func destroyView(_ s: Slot) {
s.listener = nil
s.view.destroy()
s.view.removeFromSuperview()
}
/// Q4: recreate adaptive banners whose safe-area width changed; keeps id, layout, visibility; reloads if loaded.
private func recreateChangedAdaptive() {
adaptiveCheck = nil
guard let overlay = host?.overlay() else { return }
let vc = host?.hostViewController()
for s in slots.values {
let width = currentAdaptiveWidth(s, overlay)
if !followsWidth(s) || width == s.adaptiveWidthUsed || width <= 0 { continue }
destroyView(s)
do { try buildView(s, overlay) } catch { continue }
relayout(s, overlay)
if s.loadRequested, let vc = vc { s.view.loadAd(with: vc) }
if !s.visible { s.view.pauseAutoRefresh() }
}
}
private func result(_ s: Slot) -> [String: Any] {
return ["bannerId": s.bannerId, "adSize": Mappers.adSize(s.adSize), "frame": Mappers.rect(s.frame), "visible": s.visible]
}
fileprivate func emit(_ name: String, _ slot: Slot, _ view: LPMBannerAdView, _ info: LPMAdInfo?, _ error: Error?) {
// Callbacks of a view that was replaced (Q4) or destroyed are dropped.
guard slot.view === view, slots[slot.bannerId] === slot else { return }
var o: [String: Any] = ["bannerId": slot.bannerId, "adUnitId": slot.adUnitId, "frame": Mappers.rect(slot.frame)]
if let info = info { o["adInfo"] = Mappers.adInfo(info) }
if let error = error { o["error"] = Mappers.error(error) }
host?.emit(name, o)
}
/// One delegate per view (the SDK holds it weakly; the slot keeps it alive).
final class Listener: NSObject, LPMBannerAdViewDelegate {
private weak var manager: BannerManager?
private weak var slot: Slot?
private weak var view: LPMBannerAdView?
init(manager: BannerManager, slot: Slot, view: LPMBannerAdView) {
self.manager = manager
self.slot = slot
self.view = view
}
private func post(_ name: String, _ info: LPMAdInfo?, _ error: Error?) {
DispatchQueue.main.async { [weak self] in
guard let self = self, let slot = self.slot, let view = self.view else { return }
self.manager?.emit(name, slot, view, info, error)
}
}
@objc(didLoadAdWithAdInfo:) func didLoadAd(with adInfo: LPMAdInfo) { post("bannerLoaded", adInfo, nil) }
@objc(didFailToLoadAdWithAdUnitId:error:) func didFailToLoadAd(withAdUnitId adUnitId: String, error: Error) {
post("bannerLoadFailed", nil, error)
}
@objc(didDisplayAdWithAdInfo:) func didDisplayAd(with adInfo: LPMAdInfo) { post("bannerDisplayed", adInfo, nil) }
@objc(didFailToDisplayAdWithAdInfo:error:) func didFailToDisplayAd(with adInfo: LPMAdInfo, error: Error) {
post("bannerDisplayFailed", adInfo, error)
}
@objc(didClickAdWithAdInfo:) func didClickAd(with adInfo: LPMAdInfo) { post("bannerClicked", adInfo, nil) }
@objc(didExpandAdWithAdInfo:) func didExpandAd(with adInfo: LPMAdInfo) { post("bannerExpanded", adInfo, nil) }
@objc(didCollapseAdWithAdInfo:) func didCollapseAd(with adInfo: LPMAdInfo) { post("bannerCollapsed", adInfo, nil) }
@objc(didLeaveAppWithAdInfo:) func didLeaveApp(with adInfo: LPMAdInfo) { post("bannerLeftApplication", adInfo, nil) }
}
}

View file

@ -0,0 +1,65 @@
import Foundation
/// A promise rejection with one of the plugin's string codes (INVALID_ARGUMENT, NOT_FOUND ...).
struct CallError: Error {
let code: String
let message: String
init(_ code: String, _ message: String) {
self.code = code
self.message = message
}
static func invalid(_ message: String) -> CallError {
return CallError("INVALID_ARGUMENT", message)
}
static func notFound(_ what: String, _ id: String) -> CallError {
return CallError("NOT_FOUND", "\(what) '\(id)' not found")
}
}
/// Typed reads from a Capacitor options dictionary. JS booleans arrive as CFBoolean-backed NSNumbers and are told
/// apart from numbers, so the checks match the Android bridge (where Boolean is not a Number).
enum Args {
static func isBool(_ v: Any?) -> Bool {
guard let n = v as? NSNumber else { return false }
return CFGetTypeID(n) == CFBooleanGetTypeID()
}
static func number(_ v: Any?) -> Double? {
guard let n = v as? NSNumber, !isBool(n) else { return nil }
return n.doubleValue
}
static func present(_ o: [String: Any], _ key: String) -> Bool {
guard let v = o[key] else { return false }
return !(v is NSNull)
}
static func string(_ o: [String: Any], _ key: String) -> String? {
return o[key] as? String
}
static func nonEmpty(_ o: [String: Any], _ key: String) -> String? {
guard let s = o[key] as? String, !s.isEmpty else { return nil }
return s
}
static func object(_ o: [String: Any], _ key: String) -> [String: Any]? {
return o[key] as? [String: Any]
}
static func finite(_ o: [String: Any], _ key: String) throws -> Double {
guard let d = number(o[key]) else { throw CallError.invalid("\(key) must be a number") }
if !d.isFinite { throw CallError.invalid("\(key) must be finite") }
return d
}
static func positiveInt(_ o: [String: Any], _ label: String, _ key: String) throws -> Int {
guard let d = number(o[key]), d >= 1, d.isFinite else {
throw CallError.invalid("\(label) must be a positive number")
}
return Int(d.rounded())
}
}

View file

@ -3,8 +3,9 @@ import Capacitor
import Foundation import Foundation
import IronSource import IronSource
/// Capacitor bridge for the Unity LevelPlay SDK (ad-unit API: `LPMRewardedAd` / `LPMInterstitialAd`). /// Capacitor bridge for the Unity LevelPlay SDK (ad-unit API: `LPMRewardedAd` / `LPMInterstitialAd` /
/// Rewarded and interstitial only. All LevelPlay calls run on the main thread. /// `LPMBannerAdView`, plus `LevelPlayNativeAd`). Every SDK call and every view operation runs on the main thread;
/// plugin state is only touched there.
@objc(LevelPlayPlugin) @objc(LevelPlayPlugin)
public class LevelPlayPlugin: CAPPlugin, CAPBridgedPlugin { public class LevelPlayPlugin: CAPPlugin, CAPBridgedPlugin {
public let identifier = "LevelPlayPlugin" public let identifier = "LevelPlayPlugin"
@ -22,14 +23,72 @@ public class LevelPlayPlugin: CAPPlugin, CAPBridgedPlugin {
CAPPluginMethod(name: "showInterstitial", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "showInterstitial", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "isReady", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "isReady", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "launchTestSuite", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "launchTestSuite", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "validateIntegration", returnType: CAPPluginReturnPromise) CAPPluginMethod(name: "validateIntegration", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "getCapabilities", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "setSegment", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "setDynamicUserId", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "isPlacementCapped", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "getReward", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "createBanner", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "loadBanner", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "showBanner", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "hideBanner", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "setBannerLayout", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "destroyBanner", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "loadNativeAd", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "showNativeAd", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "setNativeAdRect", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "hideNativeAd", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "destroyNativeAd", returnType: CAPPluginReturnPromise)
] ]
/// Impressions kept while no JS impressionData listener exists (owner decision Q2); the oldest is dropped.
static let impressionQueueCap = 100
static let eventImpression = "impressionData"
private enum InitState { case idle, running, done } private enum InitState { case idle, running, done }
private var initState = InitState.idle private var initState = InitState.idle
private var pendingInits: [CAPPluginCall] = [] private var pendingInits: [CAPPluginCall] = []
private var rewarded: [String: RewardedHolder] = [:] private var rewarded: [String: RewardedHolder] = [:]
private var interstitials: [String: InterstitialHolder] = [:] private var interstitials: [String: InterstitialHolder] = [:]
private var impressionQueue: [[String: Any]] = []
private var overlayHost: OverlayHost?
/// Attached to every rewarded, interstitial and banner object (per-ad delegates, owner decision Q1).
private(set) lazy var impressionForwarder = ImpressionForwarder(plugin: self)
// Created on first use (not lazy vars: deinit must not create them while self is deallocating).
private var bannerStore: BannerManager?
private var nativeAdStore: NativeAdManager?
private var banners: BannerManager {
if let m = bannerStore { return m }
let m = BannerManager(impressionDelegate: impressionForwarder)
m.host = self
bannerStore = m
return m
}
private var nativeAds: NativeAdManager {
if let m = nativeAdStore { return m }
let m = NativeAdManager()
m.host = self
m.onImpression = { [weak self] data in self?.emitImpression(data) }
m.webRoot = { [weak self] in self?.bridge?.config.appLocation }
nativeAdStore = m
return m
}
deinit {
// Plugin unload: destroy every banner and native ad on the main thread (design §6.6).
let banners = bannerStore
let nativeAds = nativeAdStore
let overlay = overlayHost
let cleanup = {
banners?.destroyAll()
nativeAds?.destroyAll()
overlay?.detach()
}
if Thread.isMainThread { cleanup() } else { DispatchQueue.main.async(execute: cleanup) }
}
// MARK: - Init / settings // MARK: - Init / settings
@ -244,18 +303,266 @@ public class LevelPlayPlugin: CAPPlugin, CAPBridgedPlugin {
} }
static func info(_ adInfo: LPMAdInfo?) -> [String: Any] { static func info(_ adInfo: LPMAdInfo?) -> [String: Any] {
guard let i = adInfo else { return [:] } return Mappers.adInfo(adInfo)
var out: [String: Any] = ["adId": i.adId, "adUnitId": i.adUnitId, "adUnitName": i.adUnitName,
"adFormat": i.adFormat, "adNetwork": i.adNetwork, "instanceName": i.instanceName,
"instanceId": i.instanceId, "country": i.country, "auctionId": i.auctionId,
"precision": i.precision, "revenue": i.revenue.doubleValue]
if let placement = i.placementName { out["placementName"] = placement }
return out
} }
static func error(_ error: Error) -> [String: Any] { static func error(_ error: Error) -> [String: Any] {
let e = error as NSError return Mappers.error(error)
return ["code": e.code, "message": e.localizedDescription] }
/// Runs on the main thread; a CallError rejects the call with its code.
private func onMain(_ call: CAPPluginCall, _ task: @escaping () throws -> Void) {
DispatchQueue.main.async {
do {
try task()
} catch let e as CallError {
call.reject(e.message, e.code)
} catch {
call.reject(error.localizedDescription, "ERROR", error)
}
}
}
// MARK: - 0.3.0: capabilities, user
@objc func getCapabilities(_ call: CAPPluginCall) {
call.resolve(["banner": true, "nativeAd": true, "nativeAdTemplates": ["small", "medium"],
"impressionData": true, "adInfoChanged": true])
}
@objc func setSegment(_ call: CAPPluginCall) {
let o = call.options as? [String: Any] ?? [:]
let segment = LPMSegment()
do {
if let name = o["segmentName"] as? String { segment.segmentName = name }
if Args.present(o, "level") {
let level = try Args.finite(o, "level")
if level != level.rounded() { throw CallError.invalid("level must be an integer") }
segment.level = Int32(clamping: Int(level))
}
if Args.present(o, "isPaying") {
guard Args.isBool(o["isPaying"]), let paying = o["isPaying"] as? Bool else {
throw CallError.invalid("isPaying must be a boolean")
}
segment.paying = paying
}
if Args.present(o, "userCreationDate") {
let ms = try Args.finite(o, "userCreationDate")
segment.userCreationDate = Date(timeIntervalSince1970: ms / 1000)
}
if Args.present(o, "iapTotal") { segment.iapTotal = try Args.finite(o, "iapTotal") }
if Args.present(o, "customParameters") {
guard let custom = o["customParameters"] as? [String: Any] else {
throw CallError.invalid("customParameters must be an object of strings")
}
let pairs = custom.map { ($0.key, $0.value) }.sorted { $0.0 < $1.0 }
if let err = OverlayMath.customParamsError(pairs) { throw CallError.invalid(err) }
for (k, v) in pairs { segment.setCustomValue(v as? String ?? "", forKey: k) }
}
} catch let e as CallError {
call.reject(e.message, e.code)
return
} catch {
call.reject(error.localizedDescription, "ERROR", error)
return
}
DispatchQueue.main.async {
LevelPlay.setSegment(segment)
call.resolve()
}
}
@objc func setDynamicUserId(_ call: CAPPluginCall) {
guard let userId = call.getString("userId"), !userId.isEmpty else {
call.reject("userId is required", "INVALID_ARGUMENT")
return
}
DispatchQueue.main.async {
call.resolve(["valid": LevelPlay.setDynamicUserId(userId)])
}
}
@objc func isPlacementCapped(_ call: CAPPluginCall) {
let format = call.getString("format")
guard format == "rewarded" || format == "interstitial" else {
call.reject("format must be 'rewarded' or 'interstitial'", "INVALID_ARGUMENT")
return
}
guard let placement = call.getString("placementName"), !placement.isEmpty else {
call.reject("placementName is required", "INVALID_ARGUMENT")
return
}
DispatchQueue.main.async {
let capped = format == "interstitial"
? LPMInterstitialAd.isPlacementCapped(placement)
: LPMRewardedAd.isPlacementCapped(placement)
call.resolve(["capped": capped])
}
}
@objc func getReward(_ call: CAPPluginCall) {
guard let adUnitId = requireAdUnit(call) else { return }
let placement = call.getString("placementName")
DispatchQueue.main.async {
let ad = self.rewardedHolder(adUnitId).ad
let reward = ad.getReward(placementName: placement?.isEmpty == false ? placement : nil)
call.resolve(Mappers.reward(reward))
}
}
// MARK: - 0.3.0: banners
@objc func createBanner(_ call: CAPPluginCall) {
let o = call.options as? [String: Any] ?? [:]
onMain(call) { call.resolve(try self.banners.create(o)) }
}
@objc func loadBanner(_ call: CAPPluginCall) {
let id = call.getString("bannerId")
onMain(call) {
try self.banners.load(id)
call.resolve()
}
}
@objc func showBanner(_ call: CAPPluginCall) {
let id = call.getString("bannerId")
onMain(call) { call.resolve(try self.banners.show(id)) }
}
@objc func hideBanner(_ call: CAPPluginCall) {
let id = call.getString("bannerId")
onMain(call) {
self.banners.hide(id)
call.resolve()
}
}
@objc func setBannerLayout(_ call: CAPPluginCall) {
let o = call.options as? [String: Any] ?? [:]
onMain(call) { call.resolve(try self.banners.setLayout(o)) }
}
@objc func destroyBanner(_ call: CAPPluginCall) {
let id = call.getString("bannerId")
onMain(call) {
self.banners.destroy(id)
call.resolve()
}
}
// MARK: - 0.3.0: native ads
@objc func loadNativeAd(_ call: CAPPluginCall) {
let o = call.options as? [String: Any] ?? [:]
onMain(call) {
try self.nativeAds.load(o)
call.resolve()
}
}
@objc func showNativeAd(_ call: CAPPluginCall) {
let id = call.getString("nativeAdId")
let rect = call.getObject("rect")
onMain(call) {
try self.nativeAds.show(id, rect)
call.resolve()
}
}
@objc func setNativeAdRect(_ call: CAPPluginCall) {
let id = call.getString("nativeAdId")
let rect = call.getObject("rect")
onMain(call) {
try self.nativeAds.setRect(id, rect)
call.resolve()
}
}
@objc func hideNativeAd(_ call: CAPPluginCall) {
let id = call.getString("nativeAdId")
onMain(call) {
try self.nativeAds.hide(id)
call.resolve()
}
}
@objc func destroyNativeAd(_ call: CAPPluginCall) {
let id = call.getString("nativeAdId")
onMain(call) {
self.nativeAds.destroy(id)
call.resolve()
}
}
// MARK: - Overlay
/// Main thread. The pass-through overlay above the WebView, attached on first use (design §6.2).
func overlay() -> OverlayHost? {
if let host = overlayHost, host.superview != nil { return host }
guard let webView = bridge?.webView else { return nil }
let host = OverlayHost.attach(to: webView) { [weak self] in self?.onOverlayLayoutChanged() }
overlayHost = host
return host
}
private func onOverlayLayoutChanged() {
guard let overlay = overlayHost else { return }
banners.onLayoutChanged(overlay)
nativeAds.onLayoutChanged(overlay)
}
// MARK: - Impression data
/// Main thread. Sends directly when a JS listener exists, otherwise queues (capped, oldest dropped).
func emitImpression(_ data: [String: Any]) {
if hasListeners(Self.eventImpression) {
notifyListeners(Self.eventImpression, data: data)
return
}
impressionQueue.append(data)
if impressionQueue.count > Self.impressionQueueCap {
impressionQueue.removeFirst(impressionQueue.count - Self.impressionQueueCap)
}
}
private func flushImpressions() {
while !impressionQueue.isEmpty && hasListeners(Self.eventImpression) {
notifyListeners(Self.eventImpression, data: impressionQueue.removeFirst())
}
}
/// Same as CAPPlugin.addListener, then flushes impressions queued before the first impressionData listener.
override public func addListener(_ call: CAPPluginCall) {
super.addListener(call)
if call.getString("eventName") == Self.eventImpression {
DispatchQueue.main.async { self.flushImpressions() }
}
}
}
extension LevelPlayPlugin: AdHost {
func hostViewController() -> UIViewController? {
return bridge?.viewController
}
var initialized: Bool {
return initState == .done
}
}
/// The plugin's per-ad impression delegate (set on every rewarded, interstitial and banner object). The SDK holds it
/// weakly; the plugin keeps it alive.
final class ImpressionForwarder: NSObject, LPMImpressionDataDelegate {
private weak var plugin: LevelPlayPlugin?
init(plugin: LevelPlayPlugin) {
self.plugin = plugin
}
@objc(impressionDataDidSucceed:) func impressionDataDidSucceed(_ impressionData: LPMImpressionData) {
let data = Mappers.impression(impressionData)
DispatchQueue.main.async { [weak self] in self?.plugin?.emitImpression(data) }
} }
} }
@ -278,6 +585,7 @@ final class RewardedHolder: NSObject, LPMRewardedAdDelegate {
self.ad = LPMRewardedAd(adUnitId: adUnitId) self.ad = LPMRewardedAd(adUnitId: adUnitId)
super.init() super.init()
ad.setDelegate(self) ad.setDelegate(self)
ad.setImpressionDataDelegate(plugin.impressionForwarder)
} }
func begin(_ call: CAPPluginCall) { func begin(_ call: CAPPluginCall) {
@ -347,7 +655,7 @@ final class RewardedHolder: NSObject, LPMRewardedAdDelegate {
} }
} }
func didChangeAdInfo(_ adInfo: LPMAdInfo) {} func didChangeAdInfo(_ adInfo: LPMAdInfo) { plugin?.emit("adInfoChanged", base(adInfo)) }
} }
final class InterstitialHolder: NSObject, LPMInterstitialAdDelegate { final class InterstitialHolder: NSObject, LPMInterstitialAdDelegate {
@ -364,6 +672,7 @@ final class InterstitialHolder: NSObject, LPMInterstitialAdDelegate {
self.ad = LPMInterstitialAd(adUnitId: adUnitId) self.ad = LPMInterstitialAd(adUnitId: adUnitId)
super.init() super.init()
ad.setDelegate(self) ad.setDelegate(self)
ad.setImpressionDataDelegate(plugin.impressionForwarder)
} }
func begin(_ call: CAPPluginCall) { func begin(_ call: CAPPluginCall) {
@ -416,5 +725,5 @@ final class InterstitialHolder: NSObject, LPMInterstitialAdDelegate {
finish() finish()
} }
func didChangeAdInfo(_ adInfo: LPMAdInfo) {} func didChangeAdInfo(_ adInfo: LPMAdInfo) { plugin?.emit("adInfoChanged", base(adInfo)) }
} }

View file

@ -0,0 +1,102 @@
import Capacitor
import CoreGraphics
import Foundation
import IronSource
/// SDK objects to the JSON shapes of src/definitions.ts. Nil SDK values are omitted.
enum Mappers {
private static func put(_ o: inout [String: Any], _ key: String, _ value: Any?) {
guard let v = value, !(v is NSNull) else { return }
o[key] = v
}
static func adInfo(_ info: LPMAdInfo?) -> [String: Any] {
var o: [String: Any] = [:]
guard let i = info else { return o }
put(&o, "adId", i.adId as String?)
put(&o, "adUnitId", i.adUnitId as String?)
put(&o, "adUnitName", i.adUnitName as String?)
put(&o, "adFormat", i.adFormat as String?)
put(&o, "placementName", i.placementName as String?)
put(&o, "adNetwork", i.adNetwork as String?)
put(&o, "instanceName", i.instanceName as String?)
put(&o, "instanceId", i.instanceId as String?)
put(&o, "country", i.country as String?)
put(&o, "auctionId", i.auctionId as String?)
put(&o, "precision", i.precision as String?)
put(&o, "revenue", (i.revenue as NSNumber?)?.doubleValue)
put(&o, "ab", i.ab as String?)
put(&o, "segmentName", i.segmentName as String?)
put(&o, "encryptedCPM", i.encryptedCPM as String?)
put(&o, "creativeId", i.creativeId as String?)
put(&o, "conversionValue", (i.conversionValue as NSNumber?)?.doubleValue)
if let size = i.adSize as LPMAdSize? { o["adSize"] = adSize(size) }
return o
}
static func adSize(_ s: LPMAdSize) -> [String: Any] {
var o: [String: Any] = ["width": s.width, "height": s.height, "isAdaptive": s.isAdaptive]
put(&o, "description", s.sizeDescription as String?)
return o
}
static func impression(_ d: LPMImpressionData) -> [String: Any] {
var o: [String: Any] = [:]
put(&o, "adFormat", d.adFormat)
put(&o, "auctionId", d.auctionId)
put(&o, "adUnitId", d.mediationAdUnitId)
put(&o, "adUnitName", d.mediationAdUnitName)
put(&o, "adNetwork", d.adNetwork)
put(&o, "instanceName", d.instanceName)
put(&o, "instanceId", d.instanceId)
put(&o, "country", d.country)
put(&o, "placement", d.placement)
put(&o, "revenue", d.revenue?.doubleValue)
put(&o, "precision", d.precision)
put(&o, "ab", d.ab)
put(&o, "segmentName", d.segmentName)
put(&o, "encryptedCPM", d.encryptedCpm)
put(&o, "creativeId", d.creativeId)
put(&o, "conversionValue", d.conversionValue?.doubleValue)
if let all = d.allData { put(&o, "allData", JSTypes.coerceDictionaryToJSObject(all)) }
return o
}
/// Native ads use the older `ISAdInfo` (no ad unit, ad id or placement).
static func nativeAdInfo(_ info: ISAdInfo?) -> [String: Any] {
var o: [String: Any] = [:]
guard let i = info else { return o }
put(&o, "auctionId", i.auction_id as String?)
put(&o, "adNetwork", i.ad_network as String?)
put(&o, "instanceName", i.instance_name as String?)
put(&o, "instanceId", i.instance_id as String?)
put(&o, "country", i.country as String?)
put(&o, "revenue", (i.revenue as NSNumber?)?.doubleValue)
put(&o, "precision", i.precision as String?)
put(&o, "ab", i.ab as String?)
put(&o, "segmentName", i.segment_name as String?)
put(&o, "encryptedCPM", i.encrypted_cpm as String?)
put(&o, "conversionValue", (i.conversion_value as NSNumber?)?.doubleValue)
return o
}
/// impressionData synthesised from a native ad impression (no per-ad impression delegate for native ads in 9.6.1).
static func nativeImpression(_ info: ISAdInfo?) -> [String: Any] {
var o = nativeAdInfo(info)
o["adFormat"] = "nativead"
return o
}
static func error(_ error: Error) -> [String: Any] {
let e = error as NSError
return ["code": e.code, "message": e.localizedDescription]
}
static func reward(_ r: LPMReward?) -> [String: Any] {
return ["name": (r?.name as String?) ?? "", "amount": r?.amount ?? 0]
}
static func rect(_ r: CGRect) -> [String: Any] {
return ["x": Double(r.minX), "y": Double(r.minY), "width": Double(r.width), "height": Double(r.height)]
}
}

View file

@ -0,0 +1,236 @@
import IronSource
import UIKit
/// Native ads (design §4): one `LevelPlayNativeAd` per load and slot, rendered into the plugin's templates and placed
/// in the OverlayHost at a WebView-local CSS rect. Main thread only.
final class NativeAdManager {
weak var host: AdHost?
/// impressionData synthesised from the native ad info (no per-ad impression delegate for native ads).
var onImpression: (([String: Any]) -> Void)?
/// The web assets folder (for template font files).
var webRoot: (() -> URL?)?
private var slots: [String: Slot] = [:]
final class Slot {
let id: String
let placementName: String?
let template: String
let style: NativeAdStyle
var ad: LevelPlayNativeAd?
var listener: Listener?
var loaded = false
var view: ISNativeAdView?
var rect: CGRect?
var visible = false
init(id: String, placementName: String?, template: String, style: NativeAdStyle) {
self.id = id
self.placementName = placementName
self.template = template
self.style = style
}
}
// MARK: - API
func load(_ o: [String: Any]) throws {
let id = try requireId(Args.string(o, "nativeAdId"))
let template = Args.string(o, "template") ?? "medium"
if template != "small" && template != "medium" {
throw CallError("UNSUPPORTED", "Template '\(template)' is not supported (small, medium)")
}
let style = try NativeAdStyle.parse(Args.object(o, "style"))
let placement = Args.nonEmpty(o, "placementName")
guard let host = host, host.initialized else {
throw CallError("NOT_INITIALIZED", "Call initialize() and wait for it before loadNativeAd()")
}
guard let vc = host.hostViewController() else {
throw CallError("NO_VIEW_CONTROLLER", "No view controller to load the native ad with")
}
// "Destroy the ad object and create a new one for every new load" (Unity).
if let old = slots.removeValue(forKey: id) { destroySlot(old) }
let s = Slot(id: id, placementName: placement, template: template, style: style)
let listener = Listener(manager: self, slot: s)
let builder: LevelPlayNativeAdBuilder = LevelPlayNativeAdBuilder().withViewController(vc).withDelegate(listener)
if let placement = placement { _ = builder.withPlacementName(placement) }
guard let ad = builder.build() as LevelPlayNativeAd? else {
throw CallError("ERROR", "The SDK could not create the native ad")
}
s.ad = ad
s.listener = listener
slots[id] = s
ad.load()
}
func show(_ id: String?, _ rect: [String: Any]?) throws {
let s = try require(id)
let r = try parseRect(rect)
guard s.loaded, let ad = s.ad else { throw CallError("NOT_LOADED", "Native ad '\(s.id)' is not loaded") }
guard let overlay = host?.overlay(), host?.hostViewController() != nil else {
throw CallError("NO_VIEW_CONTROLLER", "No view controller / WebView to show the native ad in")
}
if s.view == nil {
let view = NativeAdTemplate.build(s.template, s.style, ad, webRoot: webRoot?())
view.isHidden = true
overlay.add(view)
s.view = view
}
s.rect = r
s.visible = true
place(s, overlay)
s.view?.isHidden = false
if let view = s.view { overlay.bringSubviewToFront(view) }
logFrame(s)
}
func setRect(_ id: String?, _ rect: [String: Any]?) throws {
let s = try require(id)
s.rect = try parseRect(rect)
if let overlay = host?.overlay(), s.view != nil {
place(s, overlay)
logFrame(s)
}
}
func hide(_ id: String?) throws {
let s = try require(id)
s.visible = false
s.view?.isHidden = true
}
func destroy(_ id: String?) {
guard let id = id, let s = slots.removeValue(forKey: id) else { return }
destroySlot(s)
}
func destroyAll() {
for s in slots.values { destroySlot(s) }
slots.removeAll()
}
func onLayoutChanged(_ overlay: OverlayHost) {
for s in slots.values where s.view != nil && s.rect != nil { place(s, overlay) }
}
// MARK: - Internals
private func requireId(_ id: String?) throws -> String {
guard let id = id, !id.isEmpty else { throw CallError.invalid("nativeAdId is required") }
return id
}
private func require(_ id: String?) throws -> Slot {
let key = try requireId(id)
guard let s = slots[key] else { throw CallError.notFound("Native ad", key) }
return s
}
private func parseRect(_ r: [String: Any]?) throws -> CGRect {
guard let r = r else { throw CallError.invalid("rect { x, y, width, height } is required") }
var out: [CGFloat] = []
for key in ["x", "y", "width", "height"] {
guard let d = Args.number(r[key]) else { throw CallError.invalid("rect.\(key) must be a number") }
if !d.isFinite { throw CallError.invalid("rect.\(key) must be finite") }
out.append(CGFloat(d))
}
if out[2] < 0 || out[3] < 0 { throw CallError.invalid("rect width and height must be >= 0") }
return CGRect(x: out[0], y: out[1], width: out[2], height: out[3])
}
/// Native rects are taken literally (the page laid them out), only clamped to the WebView (design §6.3).
private func place(_ s: Slot, _ overlay: OverlayHost) {
guard let view = s.view, let rect = s.rect else { return }
overlay.place(view, OverlayMath.intersect(rect, overlay.webViewCss))
}
private func logFrame(_ s: Slot) {
guard let view = s.view else { return }
view.layoutIfNeeded()
levelPlayLog.notice("nativeAd \(s.id, privacy: .public) \(s.template, privacy: .public) frame \(BannerManager.describe(view.frame), privacy: .public) visible \(s.visible, privacy: .public)")
}
private func destroySlot(_ s: Slot) {
s.view?.removeFromSuperview()
s.view = nil
s.ad?.destroy()
s.ad = nil
s.listener = nil
s.loaded = false
}
private func event(_ s: Slot, _ info: ISAdInfo?) -> [String: Any] {
var o: [String: Any] = ["nativeAdId": s.id]
if let p = s.placementName { o["placementName"] = p }
if let info = info { o["adInfo"] = Mappers.nativeAdInfo(info) }
return o
}
fileprivate func current(_ slot: Slot, _ ad: LevelPlayNativeAd) -> Bool {
return slots[slot.id] === slot && slot.ad === ad
}
fileprivate func didLoad(_ slot: Slot, _ ad: LevelPlayNativeAd, _ info: ISAdInfo?) {
guard current(slot, ad) else { return }
slot.loaded = true
host?.emit("nativeAdLoaded", event(slot, info))
}
fileprivate func didFail(_ slot: Slot, _ ad: LevelPlayNativeAd, _ error: Error) {
guard current(slot, ad) else { return }
// The failed ad object is destroyed; the slot stays (NOT_LOADED) until the next loadNativeAd().
slot.ad?.destroy()
slot.ad = nil
slot.loaded = false
var o = event(slot, nil)
o["error"] = Mappers.error(error)
host?.emit("nativeAdLoadFailed", o)
}
fileprivate func didImpression(_ slot: Slot, _ ad: LevelPlayNativeAd, _ info: ISAdInfo?) {
guard current(slot, ad) else { return }
host?.emit("nativeAdImpression", event(slot, info))
onImpression?(Mappers.nativeImpression(info))
}
fileprivate func didClick(_ slot: Slot, _ ad: LevelPlayNativeAd, _ info: ISAdInfo?) {
guard current(slot, ad) else { return }
host?.emit("nativeAdClicked", event(slot, info))
}
/// One delegate per load (the builder holds it weakly; the slot keeps it alive). Callbacks of an ad object that
/// was replaced or destroyed are dropped.
final class Listener: NSObject, LevelPlayNativeAdDelegate {
private weak var manager: NativeAdManager?
private weak var slot: Slot?
init(manager: NativeAdManager, slot: Slot) {
self.manager = manager
self.slot = slot
}
private func post(_ block: @escaping (NativeAdManager, Slot) -> Void) {
DispatchQueue.main.async { [weak self] in
guard let m = self?.manager, let s = self?.slot else { return }
block(m, s)
}
}
@objc(didLoad:withAdInfo:) func didLoad(_ nativeAd: LevelPlayNativeAd, with adInfo: ISAdInfo) {
post { $0.didLoad($1, nativeAd, adInfo) }
}
@objc(didFailToLoad:withError:) func didFail(toLoad nativeAd: LevelPlayNativeAd, withError error: Error) {
post { $0.didFail($1, nativeAd, error) }
}
@objc(didRecordImpression:withAdInfo:) func didRecordImpression(_ nativeAd: LevelPlayNativeAd, with adInfo: ISAdInfo) {
post { $0.didImpression($1, nativeAd, adInfo) }
}
@objc(didClick:withAdInfo:) func didClick(_ nativeAd: LevelPlayNativeAd, with adInfo: ISAdInfo) {
post { $0.didClick($1, nativeAd, adInfo) }
}
}
}

View file

@ -0,0 +1,65 @@
import UIKit
/// Parsed NativeAdTemplateStyle (src/definitions.ts). Sizes are CSS px (pt). Same defaults and validation as Android.
struct NativeAdStyle {
struct Font {
var family: String?
var size: CGFloat?
}
var backgroundColor = UIColor(white: 1, alpha: 1)
var titleColor = NativeAdStyle.rgb(0x202124)
var bodyColor = NativeAdStyle.rgb(0x5F6368)
var callToActionBackgroundColor = NativeAdStyle.rgb(0x1A73E8)
var callToActionTextColor = UIColor(white: 1, alpha: 1)
var cornerRadius: CGFloat = 0
var titleFont = Font()
var bodyFont = Font()
var callToActionFont = Font()
static func rgb(_ v: UInt32) -> UIColor {
return UIColor(red: CGFloat((v >> 16) & 0xFF) / 255, green: CGFloat((v >> 8) & 0xFF) / 255,
blue: CGFloat(v & 0xFF) / 255, alpha: 1)
}
static func parse(_ o: [String: Any]?) throws -> NativeAdStyle {
var s = NativeAdStyle()
guard let o = o else { return s }
s.backgroundColor = try color(o, "backgroundColor", s.backgroundColor)
s.titleColor = try color(o, "titleColor", s.titleColor)
s.bodyColor = try color(o, "bodyColor", s.bodyColor)
s.callToActionBackgroundColor = try color(o, "callToActionBackgroundColor", s.callToActionBackgroundColor)
s.callToActionTextColor = try color(o, "callToActionTextColor", s.callToActionTextColor)
if Args.present(o, "cornerRadius") {
guard let r = Args.number(o["cornerRadius"]), r >= 0 else { throw CallError.invalid("style.cornerRadius must be >= 0") }
s.cornerRadius = CGFloat(r)
}
s.titleFont = try font(o, "titleFont")
s.bodyFont = try font(o, "bodyFont")
s.callToActionFont = try font(o, "callToActionFont")
return s
}
private static func color(_ o: [String: Any], _ key: String, _ fallback: UIColor) throws -> UIColor {
if !Args.present(o, key) { return fallback }
guard let c = OverlayMath.parseColor(o[key] as? String) else {
throw CallError.invalid("style.\(key) must be #RRGGBB or #RRGGBBAA")
}
return UIColor(red: c.r, green: c.g, blue: c.b, alpha: c.a)
}
private static func font(_ o: [String: Any], _ key: String) throws -> Font {
if !Args.present(o, key) { return Font() }
guard let f = o[key] as? [String: Any] else { throw CallError.invalid("style.\(key) must be an object { family?, size? }") }
var family = f["family"] as? String
if let fam = family, fam.trimmingCharacters(in: .whitespaces).isEmpty { family = nil }
var size: CGFloat?
if Args.present(f, "size") {
guard let v = Args.number(f["size"]), v > 0, v.isFinite else {
throw CallError.invalid("style.\(key).size must be a positive number")
}
size = CGFloat(v)
}
return Font(family: family, size: size)
}
}

View file

@ -0,0 +1,309 @@
import CoreText
import IronSource
import UIKit
/// The plugin's own native ad templates (the SDK ships none, design §4.1), built in code so every style value
/// applies directly. Both draw an "Ad" badge and keep the bottom-left corner free for the network's privacy /
/// AdChoices icon. Same structure as the Android templates:
///
/// - small: [icon] [title / Ad + advertiser / body] [CTA], one row; fits rows from about 90 pt tall.
/// - medium: [icon] [title / Ad + advertiser], body, media view (fills the rest), CTA aligned right.
///
/// Texts: `levelplay_native_ad_badge` ("Ad") and `levelplay_native_ad_cta_fallback` ("Open"), overridable in the
/// app's `Localizable.strings` (the same keys as the Android string resources).
enum NativeAdTemplate {
private static let badgeBackground = NativeAdStyle.rgb(0xFFC107)
private static let badgeText = NativeAdStyle.rgb(0x202124)
private static var assetFonts: [String: String] = [:]
/// The template's asset views, created and styled but not filled.
struct Views {
let root: ISNativeAdView
let title: UILabel
let advertiser: UILabel
let body: UILabel
let icon: UIImageView
let cta: UIButton
let media: LevelPlayMediaView?
}
static var badgeTitle: String {
return Bundle.main.localizedString(forKey: "levelplay_native_ad_badge", value: "Ad", table: nil)
}
static var ctaFallback: String {
return Bundle.main.localizedString(forKey: "levelplay_native_ad_cta_fallback", value: "Open", table: nil)
}
/// Renders a loaded ad: create, fill from the ad's assets, hand the views to the SDK and register them.
static func build(_ template: String, _ style: NativeAdStyle, _ ad: LevelPlayNativeAd, webRoot: URL?) -> ISNativeAdView {
let v = create(template, style, webRoot: webRoot)
fill(v, title: ad.title, advertiser: ad.advertiser, body: ad.body, callToAction: ad.callToAction, icon: ad.icon)
v.root.adTitleView = v.title
v.root.adAdvertiserView = v.advertiser
v.root.adBodyView = v.body
v.root.adAppIcon = v.icon
v.root.adCallToActionView = v.cta
if let media = v.media { v.root.adMediaView = media }
v.root.registerNativeAdViews(ad)
return v.root
}
static func create(_ template: String, _ style: NativeAdStyle, webRoot: URL?) -> Views {
let medium = template == "medium"
let root = ISNativeAdView(frame: .zero)
root.accessibilityIdentifier = "LevelPlayNativeAd.\(template)"
root.backgroundColor = style.backgroundColor
root.layer.cornerRadius = style.cornerRadius
root.clipsToBounds = true
// The template consumes touches inside its bounds (UIView's default hitTest returns the root for points
// between asset views), so taps there do not reach the game.
let icon = UIImageView()
icon.contentMode = .scaleAspectFill
icon.backgroundColor = UIColor(white: 0, alpha: 0x14 / 255.0)
icon.layer.cornerRadius = 6
icon.clipsToBounds = true
let title = label(style.titleColor, font(style.titleFont, 15, bold: true, webRoot: webRoot))
title.numberOfLines = medium ? 2 : 1
let badge = BadgeLabel()
badge.text = badgeTitle
badge.textColor = badgeText
badge.font = font(NativeAdStyle.Font(family: style.bodyFont.family, size: 10), 10, bold: true, webRoot: webRoot)
badge.backgroundColor = badgeBackground
badge.layer.cornerRadius = 3
badge.clipsToBounds = true
badge.setContentHuggingPriority(.defaultHigh, for: .horizontal)
badge.setContentCompressionResistancePriority(.required, for: .horizontal)
let advertiser = label(style.bodyColor, font(style.bodyFont, 12, bold: false, webRoot: webRoot))
advertiser.numberOfLines = 1
let body = label(style.bodyColor, font(style.bodyFont, 12, bold: false, webRoot: webRoot))
body.numberOfLines = 2
let cta = PaddedButton(type: .custom)
cta.titleLabel?.font = font(style.callToActionFont, 13, bold: true, webRoot: webRoot)
cta.titleLabel?.lineBreakMode = .byTruncatingTail
cta.setTitleColor(style.callToActionTextColor, for: .normal)
cta.backgroundColor = style.callToActionBackgroundColor
cta.layer.cornerRadius = 6
cta.clipsToBounds = true
cta.translatesAutoresizingMaskIntoConstraints = false
cta.heightAnchor.constraint(equalToConstant: 36).isActive = true
cta.setContentHuggingPriority(.required, for: .horizontal)
cta.setContentCompressionResistancePriority(.required, for: .horizontal)
// Labels give way to the icon, the badge and the CTA when space is short (they truncate instead).
for l in [title, advertiser, body] {
l.setContentHuggingPriority(.defaultLow, for: .horizontal)
l.setContentCompressionResistancePriority(.defaultLow - 1, for: .horizontal)
}
// Badge + advertiser row; the trailing filler keeps the badge at its own width when there is no advertiser.
let filler = UIView()
filler.setContentHuggingPriority(UILayoutPriority(1), for: .horizontal)
filler.setContentCompressionResistancePriority(UILayoutPriority(1), for: .horizontal)
let adRow = UIStackView(arrangedSubviews: [badge, advertiser, filler])
adRow.axis = .horizontal
adRow.alignment = .center
adRow.spacing = 6
icon.translatesAutoresizingMaskIntoConstraints = false
var media: LevelPlayMediaView?
let pad: CGFloat = medium ? 10 : 8
let content: UIStackView
if medium {
NSLayoutConstraint.activate([icon.widthAnchor.constraint(equalToConstant: 40),
icon.heightAnchor.constraint(equalToConstant: 40)])
let texts = UIStackView(arrangedSubviews: [title, adRow])
texts.axis = .vertical
texts.alignment = .fill
let header = UIStackView(arrangedSubviews: [icon, texts])
header.axis = .horizontal
header.alignment = .center
header.spacing = 8
let m = LevelPlayMediaView(frame: .zero)
m.setContentHuggingPriority(.defaultLow - 1, for: .vertical)
m.setContentCompressionResistancePriority(.defaultLow - 1, for: .vertical)
media = m
// CTA on the right: the bottom-left corner stays free for the AdChoices icon.
let spacer = UIView()
spacer.setContentHuggingPriority(.defaultLow - 1, for: .horizontal)
let ctaRow = UIStackView(arrangedSubviews: [spacer, cta])
ctaRow.axis = .horizontal
content = UIStackView(arrangedSubviews: [header, body, m, ctaRow])
content.axis = .vertical
content.alignment = .fill
content.spacing = 8
content.setCustomSpacing(6, after: header)
for v in [header, body, ctaRow] as [UIView] {
v.setContentHuggingPriority(.required, for: .vertical)
v.setContentCompressionResistancePriority(.required, for: .vertical)
}
} else {
NSLayoutConstraint.activate([icon.widthAnchor.constraint(equalToConstant: 48),
icon.heightAnchor.constraint(equalToConstant: 48)])
let texts = UIStackView(arrangedSubviews: [title, adRow, body])
texts.axis = .vertical
texts.alignment = .fill
content = UIStackView(arrangedSubviews: [icon, texts, cta])
content.axis = .horizontal
content.alignment = .center
content.spacing = 8
}
content.translatesAutoresizingMaskIntoConstraints = false
root.addSubview(content)
let bottom = content.bottomAnchor.constraint(lessThanOrEqualTo: root.bottomAnchor, constant: -pad)
var constraints = [
content.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: pad),
content.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -pad),
content.topAnchor.constraint(greaterThanOrEqualTo: root.topAnchor, constant: pad),
bottom
]
if medium {
// Fill the height; the media view takes what the texts and the CTA leave.
let fill = content.bottomAnchor.constraint(equalTo: root.bottomAnchor, constant: -pad)
fill.priority = .defaultHigh
constraints += [content.topAnchor.constraint(equalTo: root.topAnchor, constant: pad).withPriority(.defaultHigh), fill]
} else {
constraints.append(content.centerYAnchor.constraint(equalTo: root.centerYAnchor))
}
NSLayoutConstraint.activate(constraints)
return Views(root: root, title: title, advertiser: advertiser, body: body, icon: icon, cta: cta, media: media)
}
static func fill(_ v: Views, title: String?, advertiser: String?, body: String?, callToAction: String?,
icon: ISNativeAdDataImage?) {
setOrHide(v.title, title)
setOrHide(v.advertiser, advertiser)
setOrHide(v.body, body)
let cta = (callToAction?.isEmpty == false) ? callToAction! : ctaFallback
v.cta.setTitle(cta, for: .normal)
bindIcon(v.icon, icon)
}
private static func label(_ color: UIColor, _ font: UIFont) -> UILabel {
let l = UILabel()
l.textColor = color
l.font = font
l.lineBreakMode = .byTruncatingTail
l.adjustsFontForContentSizeCategory = false
return l
}
/// System family name, or a .ttf / .otf file in the web assets (Capacitor copies the web dir to `public` in the
/// app bundle). Sizes are pt (= CSS px), not scaled by Dynamic Type, like WebView text.
static func font(_ f: NativeAdStyle.Font, _ defaultSize: CGFloat, bold: Bool, webRoot: URL?) -> UIFont {
let size = f.size ?? defaultSize
let system = UIFont.systemFont(ofSize: size, weight: bold ? .bold : .regular)
guard let family = f.family else { return system }
let lower = family.lowercased()
if lower.hasSuffix(".ttf") || lower.hasSuffix(".otf") {
guard let name = assetFontName(family, webRoot: webRoot), let font = UIFont(name: name, size: size) else {
return system
}
return font
}
if let named = UIFont(name: family, size: size) { return named }
if UIFont.familyNames.contains(family) {
var desc = UIFontDescriptor(fontAttributes: [.family: family])
if bold, let b = desc.withSymbolicTraits(.traitBold) { desc = b }
return UIFont(descriptor: desc, size: size)
}
levelPlayLog.warning("Native ad font family not found: \(family, privacy: .public); using the system font")
return system
}
/// Registers the font file once per process (CTFontManager) and returns its PostScript name.
private static func assetFontName(_ family: String, webRoot: URL?) -> String? {
var path = family
while path.hasPrefix("/") { path.removeFirst() }
if path.hasPrefix("./") { path.removeFirst(2) }
if let cached = assetFonts[path] { return cached }
let root = webRoot ?? Bundle.main.bundleURL.appendingPathComponent("public")
let url = root.appendingPathComponent(path)
guard FileManager.default.fileExists(atPath: url.path),
let descriptors = CTFontManagerCreateFontDescriptorsFromURL(url as CFURL) as? [CTFontDescriptor],
let first = descriptors.first,
let name = CTFontDescriptorCopyAttribute(first, kCTFontNameAttribute) as? String else {
levelPlayLog.warning("Native ad font not found in the web assets: \(path, privacy: .public); using the system font")
return nil
}
var error: Unmanaged<CFError>?
if !CTFontManagerRegisterFontsForURL(url as CFURL, .process, &error) {
// kCTFontManagerErrorAlreadyRegistered (105) is fine; anything else falls back below if UIFont fails.
_ = error?.takeRetainedValue()
}
assetFonts[path] = name
return name
}
private static func setOrHide(_ v: UILabel, _ text: String?) {
if let t = text, !t.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
v.text = t
v.isHidden = false
} else {
v.text = ""
v.isHidden = true
}
}
private static func bindIcon(_ view: UIImageView, _ image: ISNativeAdDataImage?) {
guard let image = image else {
view.isHidden = true
return
}
if let img = image.image {
view.image = img
return
}
guard let url = image.url, let scheme = url.scheme, scheme.hasPrefix("http") else {
view.isHidden = true
return
}
// Some adapters only give a URL: fetch it off the main thread.
URLSession.shared.dataTask(with: url) { [weak view] data, _, _ in
let img = data.flatMap { UIImage(data: $0) }
DispatchQueue.main.async {
guard let view = view else { return }
if let img = img { view.image = img } else { view.isHidden = true }
}
}.resume()
}
}
/// "Ad" badge: a label with 4 pt horizontal padding.
final class BadgeLabel: UILabel {
private let inset = UIEdgeInsets(top: 1, left: 4, bottom: 1, right: 4)
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: inset))
}
override var intrinsicContentSize: CGSize {
let s = super.intrinsicContentSize
return CGSize(width: s.width + inset.left + inset.right, height: s.height + inset.top + inset.bottom)
}
}
/// CTA button with 12 pt horizontal padding (without the iOS 15 deprecated `contentEdgeInsets`).
final class PaddedButton: UIButton {
override var intrinsicContentSize: CGSize {
let s = super.intrinsicContentSize
return CGSize(width: s.width + 24, height: s.height)
}
}
private extension NSLayoutConstraint {
func withPriority(_ p: UILayoutPriority) -> NSLayoutConstraint {
priority = p
return self
}
}

View file

@ -0,0 +1,72 @@
import UIKit
import os
let levelPlayLog = Logger(subsystem: "fyi.crt.capacitor.levelplay", category: "LevelPlay")
/// The plugin's pass-through overlay for banners and native ads (design §6.2). In Capacitor the bridge view
/// controller's root view is the WKWebView itself (`CAPBridgeViewController.loadView` sets `view = webView`), so the
/// overlay is added to that view, above the WebView's scroll view, filling its bounds. It therefore follows the
/// WebView's frame, safe area and modal presentations without observing anything. Its coordinate space is the
/// WebView viewport in CSS px (1 CSS px = 1 pt).
///
/// `hitTest` returns nil for points that land on the overlay itself, so touches outside ad views reach the page.
final class OverlayHost: UIView {
/// Called on the main thread after the overlay's bounds or safe area changed (and on explicit relayouts).
var onLayoutChanged: (() -> Void)?
private var lastBounds = CGRect.null
private var lastInsets = UIEdgeInsets(top: -1, left: -1, bottom: -1, right: -1)
static func attach(to webView: UIView, onLayoutChanged: @escaping () -> Void) -> OverlayHost {
let host = OverlayHost(frame: webView.bounds)
host.autoresizingMask = [.flexibleWidth, .flexibleHeight]
host.backgroundColor = .clear
host.isOpaque = false
host.clipsToBounds = false
host.accessibilityIdentifier = "LevelPlayOverlay"
host.onLayoutChanged = onLayoutChanged
webView.addSubview(host)
webView.bringSubviewToFront(host)
return host
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let hit = super.hitTest(point, with: event)
return hit === self ? nil : hit
}
override func layoutSubviews() {
super.layoutSubviews()
if bounds != lastBounds || safeAreaInsets != lastInsets {
lastBounds = bounds
lastInsets = safeAreaInsets
onLayoutChanged?()
}
}
override func safeAreaInsetsDidChange() {
super.safeAreaInsetsDidChange()
setNeedsLayout()
}
/// The WebView viewport in CSS px.
var webViewCss: CGRect { return bounds }
/// The viewport minus the system insets (status bar, notch, home indicator) in CSS px (design §6.3).
var safeAreaCss: CGRect {
return OverlayMath.intersect(bounds.inset(by: safeAreaInsets), bounds)
}
func add(_ view: UIView) {
addSubview(view)
superview?.bringSubviewToFront(self)
}
func place(_ view: UIView, _ frame: CGRect) {
if view.frame != frame { view.frame = frame }
}
func detach() {
onLayoutChanged = nil
removeFromSuperview()
}
}

View file

@ -0,0 +1,70 @@
import CoreGraphics
import Foundation
/// Pure helpers (no UIKit views, no SDK types) for overlay geometry and argument validation. Same rules as the
/// Android `OverlayMath`.
enum OverlayMath {
/// LPMSegment custom-parameter limits (read from the Android 9.6.1 bytecode, applied on both platforms).
static let maxCustomParams = 5
static let maxCustomLength = 32
/// Intersection of two rects; an empty intersection has zero width / height at the clamped origin.
static func intersect(_ a: CGRect, _ b: CGRect) -> CGRect {
let l = max(a.minX, b.minX)
let t = max(a.minY, b.minY)
let r = min(a.maxX, b.maxX)
let btm = min(a.maxY, b.maxY)
return CGRect(x: l, y: t, width: max(0, r - l), height: max(0, btm - t))
}
/// Banner frame inside `area` (design §6.4): centred horizontally, anchored top / bottom / center.
static func bannerFrame(_ area: CGRect, width: CGFloat, height: CGFloat, position: String,
offsetX: CGFloat, offsetY: CGFloat) -> CGRect {
let x = area.minX + (area.width - width) / 2 + offsetX
let y: CGFloat
switch position {
case "top": y = area.minY + offsetY
case "center": y = area.minY + (area.height - height) / 2 + offsetY
default: y = area.minY + area.height - height + offsetY
}
return CGRect(x: x, y: y, width: width, height: height)
}
static func isPosition(_ p: String) -> Bool {
return p == "top" || p == "bottom" || p == "center"
}
static func isBannerSize(_ s: String) -> Bool {
return ["BANNER", "LARGE", "MEDIUM_RECTANGLE", "LEADERBOARD", "ADAPTIVE", "CUSTOM"].contains(s)
}
/// Error message for segment custom parameters that break the SDK limits, or nil when they are fine.
static func customParamsError(_ params: [(String, Any)]) -> String? {
if params.count > maxCustomParams {
return "customParameters: at most \(maxCustomParams) pairs (got \(params.count))"
}
for (k, v) in params {
if !validToken(k) { return "customParameters: key '\(k)' must be 1-32 letters or digits" }
guard let s = v as? String else { return "customParameters: value of '\(k)' must be a string" }
if !validToken(s) { return "customParameters: value of '\(k)' must be 1-32 letters or digits" }
}
return nil
}
private static func validToken(_ s: String) -> Bool {
guard !s.isEmpty, s.count <= maxCustomLength else { return false }
return s.unicodeScalars.allSatisfy { ($0 >= "a" && $0 <= "z") || ($0 >= "A" && $0 <= "Z") || ($0 >= "0" && $0 <= "9") }
}
/// CSS `#RRGGBB` / `#RRGGBBAA` to RGBA components in 0...1, or nil when malformed.
static func parseColor(_ css: String?) -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)? {
guard let css = css, css.hasPrefix("#"), css.count == 7 || css.count == 9 else { return nil }
let hex = String(css.dropFirst())
guard hex.allSatisfy({ $0.isHexDigit }), let v = UInt64(hex, radix: 16) else { return nil }
if hex.count == 6 {
return (CGFloat((v >> 16) & 0xFF) / 255, CGFloat((v >> 8) & 0xFF) / 255, CGFloat(v & 0xFF) / 255, 1)
}
return (CGFloat((v >> 24) & 0xFF) / 255, CGFloat((v >> 16) & 0xFF) / 255, CGFloat((v >> 8) & 0xFF) / 255,
CGFloat(v & 0xFF) / 255)
}
}