Show ads in your app or website

Ads download once and keep showing without internet. Views and taps sync when the device is back online.

How it works

  1. Copy the API key from your app's page in My apps. Every app and website has its own key.
  2. When the device is online, download the ads with GET /api/v1/ads and save them, with their images, on the device.
  3. Show a saved ad whose starts_at / ends_at covers the current time. Pick by placement: banner, native, interstitial or splash.
  4. Count views and taps on the device. When it's online again, send them with POST /api/v1/ads/events.
  5. Download again every 6 hours (refresh_after_seconds).

iOS (Swift)

iOS

Add this file to your Xcode project. Call AppAds.shared.refresh() at launch, and AppAds.shared.ad(for: .banner) when you want to show an ad.

import Foundation

struct AppAd: Codable, Identifiable {
    let campaign_id: Int
    let placement: String
    let app_name: String
    let headline: String
    let body: String?
    let image_url: String?
    let target_url: String
    let starts_at: Date
    let ends_at: Date
    var id: Int { campaign_id }
}

final class AppAds {
    static let shared = AppAds()
    enum Placement: String { case banner, native, interstitial, splash }

    private let apiKey = "YOUR_API_KEY"
    private let baseURL = URL(string: "http://localhost:8000/api/v1")!
    private let store = UserDefaults.standard
    private var decoder: JSONDecoder { let d = JSONDecoder(); d.dateDecodingStrategy = .iso8601; return d }
    private var encoder: JSONEncoder { let e = JSONEncoder(); e.dateEncodingStrategy = .iso8601; return e }

    /// Download ads while online. Saved ads keep working offline.
    func refresh() {
        var request = URLRequest(url: baseURL.appendingPathComponent("ads"))
        request.setValue(apiKey, forHTTPHeaderField: "X-App-Key")
        URLSession.shared.dataTask(with: request) { data, _, _ in
            struct Payload: Codable { let data: [AppAd] }
            guard let data, let payload = try? self.decoder.decode(Payload.self, from: data) else { return }
            self.store.set(try? self.encoder.encode(payload.data), forKey: "appads.ads")
            payload.data.compactMap { $0.image_url.flatMap(URL.init) }.forEach { url in
                URLSession.shared.dataTask(with: url).resume() // warms URLCache for offline images
            }
            self.flush()
        }.resume()
    }

    /// A random ad for the placement that is running right now, or nil.
    func ad(for placement: Placement) -> AppAd? {
        guard let data = store.data(forKey: "appads.ads"),
              let ads = try? decoder.decode([AppAd].self, from: data) else { return nil }
        let now = Date()
        let live = ads.filter { $0.starts_at <= now && $0.ends_at > now }
        guard let ad = live.filter({ $0.placement == placement.rawValue }).randomElement() ?? live.randomElement() else { return nil }
        count(ad, "impressions")
        return ad
    }

    /// Call when the user taps the ad, then open ad.target_url.
    func tapped(_ ad: AppAd) { count(ad, "clicks"); flush() }

    private func count(_ ad: AppAd, _ field: String) {
        var events = store.dictionary(forKey: "appads.events") as? [String: [String: Int]] ?? [:]
        var entry = events["\(ad.campaign_id)"] ?? ["campaign_id": ad.campaign_id, "impressions": 0, "clicks": 0]
        entry[field, default: 0] += 1
        events["\(ad.campaign_id)"] = entry
        store.set(events, forKey: "appads.events")
    }

    /// Sends saved views and taps. Safe to call often; does nothing offline.
    func flush() {
        guard let events = store.dictionary(forKey: "appads.events") as? [String: [String: Int]], !events.isEmpty else { return }
        var request = URLRequest(url: baseURL.appendingPathComponent("ads/events"))
        request.httpMethod = "POST"
        request.setValue(apiKey, forHTTPHeaderField: "X-App-Key")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = try? JSONSerialization.data(withJSONObject: ["events": Array(events.values)])
        URLSession.shared.dataTask(with: request) { _, response, _ in
            if (response as? HTTPURLResponse)?.statusCode == 200 { self.store.removeObject(forKey: "appads.events") }
        }.resume()
    }
}

Android (Kotlin)

Android

Uses only the Android SDK and org.json. Call AppAds.refresh(context) on a background thread at launch, and AppAds.ad(context, "banner") to get an ad.

import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
import java.time.Instant

object AppAds {
    private const val API_KEY = "YOUR_API_KEY"
    private const val BASE = "http://localhost:8000/api/v1"

    private fun prefs(c: Context) = c.getSharedPreferences("appads", Context.MODE_PRIVATE)

    /** Run on a background thread while online. Saves ads and images for offline use. */
    fun refresh(context: Context) {
        val conn = URL("$BASE/ads").openConnection() as HttpURLConnection
        conn.setRequestProperty("X-App-Key", API_KEY)
        conn.setRequestProperty("Accept", "application/json")
        if (conn.responseCode != 200) return
        val ads = JSONObject(conn.inputStream.bufferedReader().readText()).getJSONArray("data")
        for (i in 0 until ads.length()) {
            val ad = ads.getJSONObject(i)
            val image = ad.optString("image_url")
            if (image.isNotEmpty()) {
                val file = File(context.filesDir, "appads_${ad.getInt("campaign_id")}.img")
                if (!file.exists()) URL(image).openStream().use { input -> file.outputStream().use { input.copyTo(it) } }
                ad.put("image_file", file.absolutePath) // show this file with BitmapFactory, works offline
            }
        }
        prefs(context).edit().putString("ads", ads.toString()).apply()
        flush(context)
    }

    /** A random live ad for the placement: banner, native, interstitial or splash. */
    fun ad(context: Context, placement: String): JSONObject? {
        val ads = JSONArray(prefs(context).getString("ads", "[]"))
        val now = Instant.now()
        val live = (0 until ads.length()).map { ads.getJSONObject(it) }.filter {
            Instant.parse(it.getString("starts_at")) <= now && Instant.parse(it.getString("ends_at")) > now
        }
        val ad = live.filter { it.getString("placement") == placement }.randomOrNull() ?: live.randomOrNull()
        ad?.let { count(context, it.getInt("campaign_id"), "impressions") }
        return ad
    }

    /** Call when the user taps the ad, then open ad.getString("target_url"). */
    fun tapped(context: Context, ad: JSONObject) = count(context, ad.getInt("campaign_id"), "clicks")

    private fun count(context: Context, campaignId: Int, field: String) {
        val events = JSONObject(prefs(context).getString("events", "{}"))
        val entry = events.optJSONObject("$campaignId")
            ?: JSONObject().put("campaign_id", campaignId).put("impressions", 0).put("clicks", 0)
        entry.put(field, entry.getInt(field) + 1)
        events.put("$campaignId", entry)
        prefs(context).edit().putString("events", events.toString()).apply()
    }

    /** Run on a background thread. Sends saved views and taps; keeps them if offline. */
    fun flush(context: Context) {
        val events = JSONObject(prefs(context).getString("events", "{}"))
        if (events.length() == 0) return
        val list = JSONArray().apply { events.keys().forEach { put(events.getJSONObject(it)) } }
        val conn = URL("$BASE/ads/events").openConnection() as HttpURLConnection
        conn.requestMethod = "POST"
        conn.doOutput = true
        conn.setRequestProperty("X-App-Key", API_KEY)
        conn.setRequestProperty("Content-Type", "application/json")
        conn.outputStream.use { it.write(JSONObject().put("events", list).toString().toByteArray()) }
        if (conn.responseCode == 200) prefs(context).edit().remove("events").apply()
    }
}

Website

Website

Add your website in My apps (choose "Website"), then paste this where the ad should appear. Ads are saved in the browser, so they still show if the visitor goes offline.

<!-- Where the ad appears: banner, native, interstitial or splash -->
<div data-appads-placement="banner"></div>

<!-- Once per page, before </body> -->
<script src="http://localhost:8000/embed.js" data-key="YOUR_API_KEY" async></script>

A website key is visible in the page source. It can only read your ads and report views, so that's fine.

API reference

Send your key in the X-App-Key header. Limit: 120 requests per minute.

GET /api/v1/ads

{
  "data": [{
    "campaign_id": 12,
    "placement": "banner",
    "app_name": "RoadTick: Driving Theory Test",
    "headline": "Pass your UK driving theory test",
    "body": "Practice questions and mock tests…",
    "image_url": "https://…/icon.jpg",
    "target_url": "https://apps.apple.com/…",
    "starts_at": "2026-09-24T18:00:00+05:00",
    "ends_at": "2026-10-24T18:00:00+05:00"
  }],
  "meta": { "app": "Arabic Calligraphy Generator", "refresh_after_seconds": 21600 }
}

POST /api/v1/ads/events

{ "events": [ { "campaign_id": 12, "impressions": 40, "clicks": 3 } ] }