-
Go to Project Settings -> General -> Frameworks, Libraries, and Embedded Content:
-
Click on the + button and select Add Other... -> Add Package Dependency...:
-
On the search bar, type the URL of this repository:
https://github.com/CleverAdvertising/swift-ads-package.git
-
Add the following line to your
Podfile
:pod 'swift-ads-package', '~> 1.0.8'
-
Run the following command to install the Swift Ads Package:
pod install
-
Create a file named AdsWebView.swift
-
Insert the following code
import Foundation
import SwiftUI
import WebKit
import swift_ads_package
import Combine
struct AdsWebView: UIViewRepresentable {
let scriptId: Int
func makeUIView(context: Context) -> WKWebView {
let webView = SwiftAdsPackage(frame: .zero, configuration: WKWebViewConfiguration(), scriptId: scriptId)
return webView
}
func updateUIView(_ uiView: WKWebView, context: Context) {
// Handle updates if necessary
}
}
- Add the following code anywhere in your project to display the ad
AdsWebView(scriptId: script id here).frame(width: 320, height: 50)
-
Create a file named AdsWebViewController.swift
-
Insert the following code
import UIKit
import WebKit
import swift_ads_package
class AdsWebViewController: UIViewController {
var scriptId: Int
var webViewWidth: CGFloat
var webViewHeight: CGFloat
init(scriptId: Int, width: CGFloat, height: CGFloat) {
self.scriptId = scriptId
self.webViewWidth = width
self.webViewHeight = height
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
let webView = SwiftAdsPackage(frame: .zero, configuration: WKWebViewConfiguration(), scriptId: scriptId)
// Adjusting the frame to the specified dimensions
webView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(webView)
// Configuring constraints for the WebView layout
NSLayoutConstraint.activate([
webView.widthAnchor.constraint(equalToConstant: webViewWidth),
webView.heightAnchor.constraint(equalToConstant: webViewHeight),
webView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
webView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
}
}
- Add the following code in your SceneDelegate project to display the ad
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
// Manually initialize the UIViewController
let window = UIWindow(windowScene: windowScene)
let adsWebViewController = AdsWebViewController(scriptId: 123, width: 320, height: 50)
window.rootViewController = adsWebViewController
window.makeKeyAndVisible()
self.window = window
}
}