Commit b2cede04 by Demid Merzlyakov

Merge branch 'feature/IOS-73-native-ads' into develop

# Conflicts:
#	1Weather.xcodeproj/project.pbxproj
#	1Weather/Ads/Configuration/AdConfig.swift
#	1Weather/Ads/Configuration/AdConfigManager.swift
parents 2719e434 fda52da8
......@@ -125,17 +125,11 @@ public class AdManager {
a9Cache.addToPreload(placementName: placementNameTodayBanner, adType: .banner, count: 1)
a9Cache.addToPreload(placementName: placementNameTodaySquare, adType: .square, count: 1)
a9Cache.addToPreload(placementName: placementNameDiscussionSquare, adType: .square, count: 1)
a9Cache.addToPreload(placementName: placementNameExtendedSquare, adType: .square, count: 1)
a9Cache.addToPreload(placementName: placementName12WeekInterstitial, adType: .interstitial, count: 1)
a9Cache.addToPreload(placementName: placementNameForecastHourlyBanner, adType: .banner, count: 1)
a9Cache.addToPreload(placementName: placementNameForecastHourlySquare, adType: .square, count: 1)
a9Cache.addToPreload(placementName: placementNameForecastExtendedBanner, adType: .banner, count: 1)
a9Cache.addToPreload(placementName: placementNameForecastExtendedSquare, adType: .square, count: 1)
a9Cache.addToPreload(placementName: placementNameForecast12WeekSquare, adType: .square, count: 1)
a9Cache.addToPreload(placementName: placementNamePrecipitationBanner, adType: .banner, count: 1)
a9Cache.addToPreload(placementName: placementNameRadarInterstitial, adType: .interstitial, count: 1)
a9Cache.addToPreload(placementName: placementNameSunMoonBanner, adType: .banner, count: 1)
a9Cache.addToPreload(placementName: placementNameForecastDailyBanner, adType: .banner, count: 1)
a9Cache.addToPreload(placementName: placementNameForecastDailySquare, adType: .square, count: 1)
a9Cache.addToPreload(placementName: placementNameNWSAlertBanner, adType: .banner, count: 1)
a9Cache.startPreloadingBids()
}
......
......@@ -12,19 +12,28 @@ import UIKit
import OneWeatherAnalytics
import OneWeatherCore
@objc
public protocol AdViewDelegate: AnyObject {
func succeeded(adView: AdView)
func failed(adView: AdView)
func succeeded(adView: AdView, hadAdBefore: Bool)
func failed(adView: AdView, hadAdBefore: Bool)
func closeButtonTapped(adView: AdView)
/// Return the view controller, that will present the interstitial.
func adTopViewController() -> UIViewController
func adTopViewController() -> UIViewController?
}
// MARK: - Default methods implementation
extension AdViewDelegate {
func closeButtonTapped(adView: AdView) {
// do nothing
}
func adTopViewController() -> UIViewController? {
return nil
}
}
@objcMembers
public class AdView: UIView {
// MARK: - Private & Internal
private var bannerView: BRNativeBannerContainerView?
private var bannerView: NativeBannerContainerView?
private lazy var autorefreshScheduler: Scheduler = {
return Scheduler(with: logName, interval: 0, onlyCountTimeWhenRunning: true) { [weak self] in
self?.requestAd(startAutorefresh: false)
......@@ -129,7 +138,7 @@ public class AdView: UIView {
log.warning("failed to guess the top view controller.")
return
}
bannerView = BRNativeBannerContainerView(adUnitId: placement.adUnitId, rootViewController: topViewController)
bannerView = NativeBannerContainerView(adUnitId: placement.adUnitId, adType: adType, rootViewController: topViewController)
if let bannerView = bannerView {
......@@ -323,25 +332,28 @@ extension AdView {
}
}
extension AdView: BRNativeBannerContainerViewDelegate {
extension AdView: NativeBannerContainerViewDelegate {
func adLoader(_ adLoader: GADAdLoader, didReceived bannerView: GAMBannerView) {
log.info("ad request succeeded")
let hadAdBefore = adReady
adReady = true
analytics(log: .ANALYTICS_AD_RECEIVED, params: self.analyticsParams)
self.delegate?.succeeded(adView: self)
self.delegate?.succeeded(adView: self, hadAdBefore: hadAdBefore)
}
func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd) {
log.info("ad request succeeded")
let hadAdBefore = adReady
adReady = true
analytics(log: .ANALYTICS_AD_RECEIVED, params: self.analyticsParams)
self.delegate?.succeeded(adView: self)
self.delegate?.succeeded(adView: self, hadAdBefore: hadAdBefore)
}
public func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: Error) {
log.error("ad request failed")
let hadAdBefore = adReady
adReady = false
self.delegate?.failed(adView: self)
self.delegate?.failed(adView: self, hadAdBefore: hadAdBefore)
}
}
......
......@@ -16,16 +16,11 @@ public struct AdConfig: Codable {
public var a9MaxCachedPerPlacement: UInt
public var placements: [AdPlacementName: AdPlacement]?
public var nativePlacements: [AdPlacementName: NativeAdPlacement]?
public func placement(named name:String) -> AdPlacement? {
return placements?[name]
}
public func nativePlacement(named name:String) -> NativeAdPlacement? {
return nativePlacements?[name]
}
struct CodingKeys: CodingKey {
var stringValue: String
init(stringValue: String) {
......@@ -89,8 +84,7 @@ extension AdConfig: Equatable {
public static func == (lhs: AdConfig, rhs: AdConfig) -> Bool {
return lhs.adsEnabled == rhs.adsEnabled &&
lhs.a9RefreshRate == rhs.a9RefreshRate &&
lhs.placements == rhs.placements &&
lhs.nativePlacements == rhs.nativePlacements
lhs.placements == rhs.placements
}
}
......@@ -104,20 +98,6 @@ extension ContentUrlConfig: Equatable {
}
}
public struct NativeAdPlacement: Codable {
public var name: String
public var adUnitId: String
public var refreshInterval: TimeInterval
public var interstitialScreenCount: Int?
enum CodingKeys: String, CodingKey {
case name
case adUnitId = "ad_unit_id"
case refreshInterval = "refresh_interval"
case interstitialScreenCount = "interstitial_screen_count"
}
}
public struct AdPlacement: Codable {
public var name: String
public var adUnitId: String
......@@ -142,12 +122,3 @@ extension AdPlacement: Equatable {
lhs.refreshInterval == rhs.refreshInterval
}
}
extension NativeAdPlacement: Equatable {
public static func == (lhs: NativeAdPlacement, rhs: NativeAdPlacement) -> Bool {
return lhs.name == rhs.name &&
lhs.adUnitId == rhs.adUnitId &&
lhs.refreshInterval == rhs.refreshInterval &&
lhs.interstitialScreenCount == rhs.interstitialScreenCount
}
}
......@@ -15,22 +15,17 @@ extension Notification.Name {
public typealias AdPlacementName = String
public let placementNameTodayBanner: AdPlacementName = "1W_iOS_Native_Banner_ForD_ATF" //TODO: wrong?
public let placementNameTodaySquare: AdPlacementName = "1W_iOS_Native_MREC_Today_BTF2"
public let placementNameDiscussionSquare: AdPlacementName = "1W_iOS_Native_MREC_Forecast_discussion"
public let placementNameExtendedSquare: AdPlacementName = "1W_iOS_Native_MREC_Forecast_discussion" // TODO: wrong?
public let placementName12WeekInterstitial: AdPlacementName = "1W_iOS_Int" //TODO: definitely wrong
public let placementNameForecastHourlyBanner: AdPlacementName = "1W_iOS_Native_Banner_Hourly_ATF"
public let placementNameForecastHourlySquare: AdPlacementName = "1W_iOS_Native_MREC_Forecast_Hourly_BTF1"
public let placementNameForecastExtendedBanner: AdPlacementName = "1W_iOS_Native_Banner_ForD_ATF" // TODO: definitely wrong
public let placementNameForecastExtendedSquare: AdPlacementName = "1W_iOS_Native_MREC_Forecast_discussion" // TODO: definitely wrong
public let placementNameForecast12WeekSquare: AdPlacementName = "1W_iOS_Native_MREC_Today_Details" //TODO: definitely wrong
public let placementNamePrecipitationBanner: AdPlacementName = "1W_iOS_Native_Banner_Precipitation_ATF"
public let placementNameRadarInterstitial: AdPlacementName = "1W_iOS_Int" //TODO: definitely wrong
public let placementNameSunMoonBanner: AdPlacementName = "1W_iOS_Native_Banner_Sunmoon_ATF"
public let placementNameTodayBanner: AdPlacementName = "today_banner"
public let placementNameTodaySquare: AdPlacementName = "today_square"
public let placementNameForecastHourlyBanner: AdPlacementName = "forecast_hourly_banner"
public let placementNameForecastHourlySquare: AdPlacementName = "forecast_hourly_square"
public let placementNameForecastDailyBanner: AdPlacementName = "forecast_daily_banner"
public let placementNameForecastDailySquare: AdPlacementName = "forecast_daily_square"
public let placementNameNWSAlertBanner: AdPlacementName = "nws_alert_banner"
public class AdConfigManager: NSObject {
@objc public static let shared = AdConfigManager()
@objc
public static let shared = AdConfigManager()
private let configManager: ConfigManager
private init(configManager: ConfigManager? = nil) {
......
//
// BRNativeBannerView.swift
// BaconReader
//
// Created by Rishab Dutta on 24/07/20.
// Copyright © 2020 OneLouder Apps. All rights reserved.
//
import Foundation
import GoogleMobileAds
class BRNativeBannerView: GADNativeAdView {
class func instantiateWithXib() -> BRNativeBannerView? {
let nib = UINib(nibName: "\(BRNativeBannerView.self)", bundle: nil)
let bView = nib.instantiate(withOwner: self, options: nil).first as? BRNativeBannerView
return bView
}
var nativeAdItem: NativeAdItem? {
didSet {
nativeAd = nativeAdItem?.nativeAd
setupView()
}
}
private func setupView() {
(headlineView as? UILabel)?.text = nativeAd?.headline
(iconView as? UIImageView)?.image = nativeAd?.icon?.image
(advertiserView as? UILabel)?.text = nativeAd?.advertiser
(callToActionView as? UILabel)?.text = nativeAd?.callToAction
}
}
......@@ -20,8 +20,8 @@ final class NativeAdItem: NSObject {
case banner
}
private var placement: NativeAdPlacement? {
return AdConfigManager.shared.adConfig.nativePlacements?.filter({ $0.value.adUnitId == adUnitId }).first?.value
private var placement: AdPlacement? {
return AdConfigManager.shared.adConfig.placements?.filter({ $0.value.adUnitId == adUnitId }).first?.value
}
private var analyticsParams: [AnalyticsParameter: Any] {
......@@ -62,9 +62,6 @@ final class NativeAdItem: NSObject {
}
func placementName() -> AdPlacementName? {
if let nativePlacement = AdConfigManager.shared.adConfig.nativePlacements?.filter({ $0.value.adUnitId == adUnitId }).first {
return nativePlacement.key
}
if let bannerPlacement = AdConfigManager.shared.adConfig.placements?.filter({ $0.value.adUnitId == adUnitId }).first {
return bannerPlacement.key
}
......
//
// NativeAdView.swift
// 1Weather
//
// Created by Demid Merzlyakov on 07.06.2021.
//
import Foundation
import GoogleMobileAds
class NativeAdView: GADNativeAdView {
@IBOutlet weak var sponsoredLabel: UILabel?
@IBOutlet weak var adChoicesViewCustomOutlet: GADAdChoicesView?
var headlineLabel: UILabel? {
headlineView as? UILabel
}
var advertiserLabel: UILabel? {
advertiserView as? UILabel
}
var bodyLabel: UILabel? {
bodyView as? UILabel
}
var iconImageView: UIImageView? {
iconView as? UIImageView
}
var callToActionLabel: UILabel? {
callToActionView as? UILabel
}
var mainImageView: UIImageView? {
imageView as? UIImageView
}
public class func instantiateWithXib(adType: AdType) -> NativeAdView? {
var xibName: String!
switch adType {
case .banner:
xibName = "NativeBannerView"
case .square:
xibName = "NativeMRECView"
case .interstitial:
assertionFailure("Incorrect ad type - interstitial")
return nil
}
let nib = UINib(nibName: xibName, bundle: nil)
let bView = nib.instantiate(withOwner: self, options: nil).first as? NativeAdView
bView?.setupPostXib()
return bView
}
func setupPostXib() {
let currentTheme = ThemeManager.currentTheme
callToActionLabel?.backgroundColor = currentTheme.nativeAdCallToActionColor
callToActionLabel?.layer.cornerRadius = 2
callToActionLabel?.clipsToBounds = true
headlineLabel?.textColor = currentTheme.primaryTextColor
advertiserLabel?.textColor = currentTheme.primaryTextColor
self.adChoicesView = self.adChoicesViewCustomOutlet
sponsoredLabel?.text = "ads.native.sponsored".localized()
sponsoredLabel?.textColor = currentTheme.primaryTextColor
bodyLabel?.textColor = currentTheme.secondaryTextColor
setupFonts()
}
private func setupFonts() {
callToActionLabel?.font = AppFont.SFCompactDisplay.regular(size: 10)
sponsoredLabel?.font = AppFont.SFCompactDisplay.regular(size: 10)
headlineLabel?.font = AppFont.SFCompactDisplay.semibold(size: 18)
advertiserLabel?.font = AppFont.SFCompactDisplay.regular(size: 12)
callToActionLabel?.font = AppFont.SFCompactDisplay.light(size: 10)
bodyLabel?.font = AppFont.SFCompactDisplay.regular(size: 10)
}
var nativeAdItem: NativeAdItem? {
willSet {
self.adChoicesView = self.adChoicesViewCustomOutlet
}
didSet {
nativeAd = nativeAdItem?.nativeAd
setupView()
}
}
private func setupView() {
headlineLabel?.text = nativeAd?.headline
iconImageView?.image = nativeAd?.icon?.image
advertiserLabel?.text = nativeAd?.advertiser
callToActionLabel?.text = nativeAd?.callToAction
bodyLabel?.text = nativeAd?.body
mainImageView?.image = nativeAd?.images?.first?.image
setupPostXib()
}
}
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="18122" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="18093"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="System colors in document resources" minToolsVersion="11.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="GADNativeAdView"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view contentMode="scaleToFill" id="A8i-el-bXZ" customClass="NativeAdView" customModule="_Weather" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="300" height="250"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="TNc-iz-mnZ">
<rect key="frame" x="0.0" y="0.0" width="300" height="155"/>
<constraints>
<constraint firstAttribute="height" constant="155" id="2of-WV-KVU"/>
<constraint firstAttribute="width" constant="300" id="fBU-Kp-e3s"/>
</constraints>
</imageView>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Headline" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="ALU-9y-yCS">
<rect key="frame" x="10" y="160" width="280" height="20"/>
<fontDescription key="fontDescription" type="system" pointSize="16"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Body" textAlignment="natural" lineBreakMode="tailTruncation" numberOfLines="2" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="b9r-uH-Qrr">
<rect key="frame" x="10" y="180" width="222" height="11"/>
<fontDescription key="fontDescription" type="system" pointSize="9"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="CTA" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="7po-us-Uyw">
<rect key="frame" x="10" y="210" width="78" height="26"/>
<color key="backgroundColor" red="0.066666666669999999" green="0.49803921569999998" blue="1" alpha="1" colorSpace="calibratedRGB"/>
<constraints>
<constraint firstAttribute="height" constant="26" id="5wk-Js-TvA"/>
<constraint firstAttribute="width" constant="78" id="mQK-sj-eIi"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="12"/>
<color key="textColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<nil key="highlightedColor"/>
</label>
<imageView clipsSubviews="YES" userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="k7n-sU-yPp">
<rect key="frame" x="236" y="184" width="54" height="54"/>
<constraints>
<constraint firstAttribute="width" constant="54" id="DaG-29-Yci"/>
<constraint firstAttribute="height" constant="54" id="Ol9-Ch-SAu"/>
</constraints>
</imageView>
</subviews>
<viewLayoutGuide key="safeArea" id="4vU-qI-YDI"/>
<color key="backgroundColor" systemColor="systemBackgroundColor"/>
<constraints>
<constraint firstItem="k7n-sU-yPp" firstAttribute="leading" secondItem="b9r-uH-Qrr" secondAttribute="trailing" constant="4" id="42b-ug-6to"/>
<constraint firstItem="TNc-iz-mnZ" firstAttribute="leading" secondItem="A8i-el-bXZ" secondAttribute="leading" id="5EK-gf-w66"/>
<constraint firstItem="7po-us-Uyw" firstAttribute="leading" secondItem="A8i-el-bXZ" secondAttribute="leading" constant="10" id="5FJ-Je-u1p"/>
<constraint firstItem="b9r-uH-Qrr" firstAttribute="top" secondItem="ALU-9y-yCS" secondAttribute="bottom" id="7uv-BN-qIz"/>
<constraint firstAttribute="bottom" secondItem="7po-us-Uyw" secondAttribute="bottom" constant="14" id="Apu-0q-oJC"/>
<constraint firstAttribute="bottom" secondItem="k7n-sU-yPp" secondAttribute="bottom" constant="12" id="CRP-vK-rgT"/>
<constraint firstAttribute="trailing" secondItem="k7n-sU-yPp" secondAttribute="trailing" constant="10" id="IBC-YR-xho"/>
<constraint firstItem="b9r-uH-Qrr" firstAttribute="leading" secondItem="ALU-9y-yCS" secondAttribute="leading" id="aoN-Pv-cUM"/>
<constraint firstItem="ALU-9y-yCS" firstAttribute="leading" secondItem="A8i-el-bXZ" secondAttribute="leading" constant="10" id="dBl-Mj-Bmh"/>
<constraint firstItem="ALU-9y-yCS" firstAttribute="top" secondItem="TNc-iz-mnZ" secondAttribute="bottom" constant="5" id="j1x-NM-1zu"/>
<constraint firstAttribute="trailing" secondItem="TNc-iz-mnZ" secondAttribute="trailing" id="o1v-BR-AAi"/>
<constraint firstAttribute="trailing" secondItem="ALU-9y-yCS" secondAttribute="trailing" constant="10" id="tNs-jB-g7c"/>
<constraint firstItem="TNc-iz-mnZ" firstAttribute="top" secondItem="A8i-el-bXZ" secondAttribute="top" id="u0g-go-6RF"/>
</constraints>
<freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
<connections>
<outlet property="bodyView" destination="b9r-uH-Qrr" id="mHO-sW-gX7"/>
<outlet property="callToActionView" destination="7po-us-Uyw" id="VBG-Fk-Pn7"/>
<outlet property="headlineView" destination="ALU-9y-yCS" id="pHO-sW-gXV"/>
<outlet property="iconView" destination="k7n-sU-yPp" id="4P6-sq-Gob"/>
<outlet property="imageView" destination="TNc-iz-mnZ" id="TN6-iz-mnZ"/>
</connections>
<point key="canvasLocation" x="214.49275362318843" y="-94.419642857142847"/>
</view>
</objects>
<resources>
<systemColor name="systemBackgroundColor">
<color white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</systemColor>
</resources>
</document>
//
// BRNativeBannerContainerView.swift
// NativeBannerContainerView.swift
// BaconReader
//
// Created by Rishab Dutta on 24/07/20.
......@@ -10,7 +10,7 @@ import Foundation
import GoogleMobileAds
import OneWeatherAnalytics
protocol BRNativeBannerContainerViewDelegate: AnyObject {
protocol NativeBannerContainerViewDelegate: AnyObject {
func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd)
func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: Error)
......@@ -18,12 +18,13 @@ protocol BRNativeBannerContainerViewDelegate: AnyObject {
func adLoader(_ adLoader: GADAdLoader, didReceived bannerView: GAMBannerView)
}
class BRNativeBannerContainerView: UIView {
private let log = AdLogger(componentName: "BRNativeBannerContainerView")
class NativeBannerContainerView: UIView {
private let log = AdLogger(componentName: "NativeBannerContainerView")
private var adLoader: NativeAdLoader
private let adType: AdType
weak var delegate: BRNativeBannerContainerViewDelegate?
weak var delegate: NativeBannerContainerViewDelegate?
public var loggingAlias: String? {
didSet {
......@@ -31,7 +32,8 @@ class BRNativeBannerContainerView: UIView {
}
}
init(adUnitId: String, rootViewController: UIViewController) {
init(adUnitId: String, adType: AdType, rootViewController: UIViewController) {
self.adType = adType
self.adLoader = NativeAdLoader(adUnitId: adUnitId, rootViewController: rootViewController, adTypes: [.native, .gamBanner])
super.init(frame: .zero)
self.adLoader.delegate = self
......@@ -47,15 +49,15 @@ class BRNativeBannerContainerView: UIView {
private func logNameUpdated() {
if let loggingAlias = self.loggingAlias {
log.componentName = "BRNativeBannerContainerView (\(loggingAlias))"
log.componentName = "NativeBannerContainerView (\(loggingAlias))"
}
else {
log.componentName = "BRNativeBannerContainerView"
log.componentName = "NativeBannerContainerView"
}
}
}
private extension BRNativeBannerContainerView {
private extension NativeBannerContainerView {
func addAsSubview(view: UIView) {
for subview in subviews {
subview.removeFromSuperview()
......@@ -74,20 +76,15 @@ private extension BRNativeBannerContainerView {
}
}
extension BRNativeBannerContainerView: NativeAdLoaderDelegate {
extension NativeBannerContainerView: NativeAdLoaderDelegate {
func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADNativeAd) {
log.debug("Banner ad recieved (native_banner) by: \(String(describing: nativeAd.responseInfo.adNetworkClassName))")
guard let nativeBannerView = BRNativeBannerView.instantiateWithXib() else { return }
guard let adView = NativeAdView.instantiateWithXib(adType: adType) else { return }
let nativeAdItem = NativeAdItem(nativeAd: nativeAd, adUnitId: adLoader.adUnitID)
nativeBannerView.nativeAdItem = nativeAdItem
addAsSubview(view: nativeBannerView)
adView.nativeAdItem = nativeAdItem
addAsSubview(view: adView)
print("native ad loader: \(String(describing: nativeAd.headline))")
delegate?.adLoader(adLoader, didReceive: nativeAd)
}
func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: Error) {
......@@ -103,7 +100,7 @@ extension BRNativeBannerContainerView: NativeAdLoaderDelegate {
}
}
extension BRNativeBannerContainerView: GADBannerViewDelegate {
extension NativeBannerContainerView: GADBannerViewDelegate {
func bannerViewDidRecordImpression(_ bannerView: GADBannerView) {
log.info("Impression")
......
//
// NativeAd.swift
// BaconReader
//
// Created by Sharad D on 16/09/19.
// Copyright © 2019 OneLouder Apps. All rights reserved.
//
import Foundation
import GoogleMobileAds
//
//class StoriesNativeAd : GADNativeAdView {
// static let AD_SIZE = CGSize(width: 320.0, height: 135.0)
//
// @IBOutlet weak var sponsoredLabel: UILabel!
// @IBOutlet weak var separator: UIView!
// @IBOutlet weak var sponsoredLabelContainerView: UIView!
//
// override var nativeAd: GADNativeAd? {
// didSet {
// setupNativeAdView()
// }
// }
//
// class func nibForAd() -> UINib! {
//
// //TODO: Temporary, update constraints instead of creating new file
// if UserDefaults.standard.bool(for: Setting.leftHandMode) {
// return UINib(nibName: "StoriesLeftNativeAd", bundle: nil)
// } else {
// return UINib(nibName: "StoriesNativeAd", bundle: nil)
// }
// }
//
// override func awakeFromNib() {
// super.awakeFromNib()
//
// sponsoredLabelContainerView.layer.cornerRadius = 4
//
// NotificationCenter.default.addObserver(self, selector: #selector(updateUI), name: NSNotification.Name(rawValue: kNotificationThemeChanged), object: nil)
//
// }
//
//
// static let desiredAssets : NSSet =
// NSSet(arrayLiteral: kAdIconImageKey, kAdTitleKey, kAdTextKey, kAdCTATextKey)
//
// override func willMove(toSuperview newSuperview: UIView?) {
// super.willMove(toSuperview: newSuperview)
// updateUI()
// }
//
// fileprivate func cellBackgorundColor() -> UIColor {
// var bgColor: UIColor
//
// let theme = BRThemeType(rawValue: Settings.shared.theme)!
// switch theme {
// case .dark:
// bgColor = UIColor(red: 17, green: 17, blue: 17)
// default:
// bgColor = UIColor(red: 247, green: 247, blue: 247)
// }
//
// return bgColor
// }
//
// private func setupNativeAdView() {
// (bodyView as? UILabel)?.text = nativeAd?.body
// (headlineView as? UILabel)?.text = nativeAd?.headline
// (iconView as? UIImageView)?.image = nativeAd?.icon?.image
// (callToActionView as? UILabel)?.text = nativeAd?.callToAction
// }
//
// @objc private func updateUI() {
//
// let sharedTheme = BRThemeManager.sharedTheme
//
// let isCompact = UserDefaults.standard.bool(for: Setting.compactMode) ;
// if isCompact {
// self.separator.heightAnchor.constraint(equalToConstant: 1.0).isActive = true
// }
// self.separator.backgroundColor = isCompact ? sharedTheme.tableViewSeparatorColor() : sharedTheme.commentSeparatorColor()
//
//
// self.backgroundColor = cellBackgorundColor()
//
// (headlineView as? UILabel)?.textColor = sharedTheme.primaryTextColor()
// (bodyView as? UILabel)?.textColor = sharedTheme.secondaryTextColor()
//
// sponsoredLabel.font = BRThemeManager.sharedTheme.storiesSubredditFont()
//
// (callToActionView as? UILabel)?.textColor = sharedTheme.secondaryTextColor()
//
// #if DEBUG
// if UserDefaults.standard.bool(for: Setting.enableAdLogging) {
// self.debugBorder(UIColor.green)
// }
// #endif
// }
//}
//
// StoriesNativeAdCell.swift
// BaconReader
//
// Created by Rishab Dutta on 27/07/20.
// Copyright © 2020 OneLouder Apps. All rights reserved.
//
import UIKit
import GoogleMobileAds
//
//class StoriesNativeAdCell: UICollectionViewCell {
//
// private var separatorHeight: CGFloat { return (UserDefaults.standard.bool(for: Setting.compactMode)) ? 1.0 : 7.0 }
//
//
// private lazy var separatorView: UIView = {
// let sv = UIView()
// sv.translatesAutoresizingMaskIntoConstraints = false
// sv.backgroundColor = (UserDefaults.standard.bool(for: Setting.compactMode)) ? BRThemeManager.sharedTheme.tableViewSeparatorColor() : BRThemeManager.sharedTheme.commentSeparatorColor()
//
// return sv
// }()
//
// private var separatorViewHeightConstraint: NSLayoutConstraint!
//
// var nativeAdView: StoriesNativeAd?
//
// var bannerAdContainerView: UIView = {
// let bView = UIView()
// bView.translatesAutoresizingMaskIntoConstraints = false
// bView.clipsToBounds = false
// return bView
// }()
//
// var nativeAdItem: NativeAdItem? {
// didSet {
//
// guard let adItem = nativeAdItem else { return }
// switch adItem.adType {
// case .native:
// nativeAdView?.nativeAd = nativeAdItem?.nativeAd
// nativeAdView?.isHidden = false
// bannerAdContainerView.isHidden = true
// case .banner:
// let bannerView = nativeAdItem?.bannerAd ?? GAMBannerView()
// addToContainer(bannerView)
// bannerView.clipsToBounds = false
// addShadow(bannerAd: bannerView)
//
// bannerAdContainerView.isHidden = false
// nativeAdView?.isHidden = true
// }
// }
// }
//
// override func awakeFromNib() {
// super.awakeFromNib()
// contentView.addSubview(separatorView)
// contentView.addSubview(bannerAdContainerView)
//
// addNativeAdToSubview()
// addBannerToSubview()
//
// NotificationCenter.default.addObserver(self, selector: #selector(updateUI), name: NSNotification.Name(rawValue: kNotificationThemeChanged), object: nil)
// }
//
//
//
// private func addBannerToSubview() {
// separatorViewHeightConstraint = separatorView.heightAnchor.constraint(equalToConstant: separatorHeight)
// NSLayoutConstraint.activate([
// separatorView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16.0),
// separatorView.topAnchor.constraint(equalTo: contentView.topAnchor),
// separatorView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
// separatorViewHeightConstraint,
//
// bannerAdContainerView.widthAnchor.constraint(equalToConstant: 320),
// bannerAdContainerView.heightAnchor.constraint(equalToConstant: 50),
// bannerAdContainerView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
// bannerAdContainerView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
// ])
// }
//
// private func addToContainer(_ bannerView: GAMBannerView) {
// bannerAdContainerView.subviews.forEach { (subview) in
// subview.removeFromSuperview()
// }
//
// bannerAdContainerView.addSubview(bannerView)
// bannerView.translatesAutoresizingMaskIntoConstraints = false
//
// NSLayoutConstraint.activate([
// bannerView.topAnchor.constraint(equalTo: bannerAdContainerView.topAnchor),
// bannerView.leadingAnchor.constraint(equalTo: bannerAdContainerView.leadingAnchor),
// bannerView.bottomAnchor.constraint(equalTo: bannerAdContainerView.bottomAnchor),
// bannerView.trailingAnchor.constraint(equalTo: bannerAdContainerView.trailingAnchor),
// ])
// }
//
// func addNativeAdToSubview() {
// nativeAdView?.subviews.forEach({ (subview) in
// subview.removeFromSuperview()
// })
//
// nativeAdView = StoriesNativeAd.nibForAd()?.instantiate(withOwner: self, options: nil).first as? StoriesNativeAd
// if let nav = nativeAdView {
// nav.translatesAutoresizingMaskIntoConstraints = false
// contentView.addSubview(nav)
// NSLayoutConstraint.activate([
// nav.topAnchor.constraint(equalTo: separatorView.bottomAnchor),
// nav.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
// nav.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
// nav.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
// ])
// }
// }
//
// private func addShadow(bannerAd: GAMBannerView) {
// let theme = BRThemeType(rawValue: Settings.shared.theme)!
//
// var shadowColor: UIColor = UIColor()
// switch theme {
// case .default:
// shadowColor = .black
// case .dark:
// shadowColor = .white
// case .light:
// shadowColor = .black
// }
// bannerAd.addShadow(with: shadowColor, alpha: 0.5, radius: 5, offset: .zero)
// }
//
// @objc private func updateUI() {
// let isCompact = UserDefaults.standard.bool(for: Setting.compactMode) ;
//
// if isCompact {
// separatorViewHeightConstraint.constant = 1
// }
//
// separatorView.backgroundColor = isCompact ? BRThemeManager.sharedTheme.tableViewSeparatorColor() : BRThemeManager.sharedTheme.commentSeparatorColor()
//
// if let bannerView = bannerAdContainerView.subviews.first as? GAMBannerView {
// addShadow(bannerAd: bannerView)
// }
// }
//}
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="16097" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="16087"/>
<capability name="collection view cell content view" minToolsVersion="11.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="StoriesNativeAdCell" id="wT6-Hq-asB" customClass="StoriesNativeAdCell" customModule="BaconReader" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="50" height="50"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<collectionViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" insetsLayoutMarginsFromSafeArea="NO" id="go0-GN-nZN">
<rect key="frame" x="0.0" y="0.0" width="50" height="50"/>
<autoresizingMask key="autoresizingMask"/>
</collectionViewCellContentView>
<point key="canvasLocation" x="58" y="-129"/>
</collectionViewCell>
</objects>
</document>
......@@ -7,7 +7,19 @@
import UIKit
extension CellFactoryProtocol {
public protocol CellFactory {
var numberOfSections:Int { get }
func numberOfRows(inSection section:Int) -> Int
func registerCells(on tableView:UITableView)
func cellFromTableView(tableView:UITableView, indexPath:IndexPath) -> UITableViewCell
}
public protocol CellFactoryDelegate {
func cellFactoryCellsChanged(_ factory: CellFactory)
}
// MARK: - Default methods implementation
extension CellFactory {
func dequeueReusableCell<T: ReusableCellProtocol>(type:T.Type, tableView:UITableView, indexPath: IndexPath) -> T {
let cell = tableView.dequeueReusableCell(withIdentifier: T.kIdentifier, for: indexPath) as! T
return cell
......@@ -17,10 +29,3 @@ extension CellFactoryProtocol {
tableView.register(type, forCellReuseIdentifier: T.kIdentifier)
}
}
public protocol CellFactoryProtocol {
var numberOfSections:Int { get }
func numberOfRows(inSection section:Int) -> Int
func registerCells(on tableView:UITableView)
func cellFromTableView(tableView:UITableView, indexPath:IndexPath) -> UITableViewCell
}
......@@ -393,6 +393,9 @@
<key>UIAppFonts</key>
<array>
<string>SF-Pro.ttf</string>
<string>SF-Compact-Display-Light.otf</string>
<string>SF-Compact-Display-Regular.otf</string>
<string>SF-Compact-Display-Semibold.otf</string>
</array>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
......
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
{
"images" : [
{
"filename" : "group4Copy2.pdf",
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
},
"properties" : {
"template-rendering-intent" : "template"
}
}
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
{
"colors" : [
{
"color" : {
"color-space" : "display-p3",
"components" : {
"alpha" : "1.000",
"blue" : "0.286",
"green" : "0.434",
"red" : "0.182"
}
},
"idiom" : "universal"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"color" : {
"color-space" : "display-p3",
"components" : {
"alpha" : "1.000",
"blue" : "0.286",
"green" : "0.434",
"red" : "0.182"
}
},
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
......@@ -268,3 +268,7 @@
// Humidity type, for smart texts
"humidity.type.high" = "high";
"humidity.type.low" = "low";
// Ads
"ads.native.sponsored" = "Sponsored";
"ads.placeholder" = "Advertisment";
......@@ -8,10 +8,10 @@
import UIKit
public struct AppFont {
private static func fontDescriptor(size:CGFloat, weight:UIFont.Weight) -> UIFontDescriptor {
private static func fontDescriptor(family: String, size:CGFloat, weight:UIFont.Weight) -> UIFontDescriptor {
let traitsDict = [UIFontDescriptor.TraitKey.weight: weight]
let descriptor = UIFontDescriptor(fontAttributes: [UIFontDescriptor.AttributeName.size : size,
UIFontDescriptor.AttributeName.family : "SF Pro",
UIFontDescriptor.AttributeName.family : family,
UIFontDescriptor.AttributeName.traits : traitsDict
])
......@@ -25,7 +25,7 @@ public struct AppFont {
if let cached = fontCache[weigth]?[size] {
return cached
}
let descriptor = AppFont.fontDescriptor(size: size, weight: weigth)
let descriptor = AppFont.fontDescriptor(family: "SF Pro", size: size, weight: weigth)
let font = UIFont(descriptor: descriptor, size: size)
if fontCache[weigth] == nil {
fontCache[weigth] = [size: font]
......@@ -52,4 +52,35 @@ public struct AppFont {
font(weigth: .semibold, size: size)
}
}
public struct SFCompactDisplay {
private static var fontCache = [UIFont.Weight: [CGFloat: UIFont]]()
static func font(weigth: UIFont.Weight, size: CGFloat) -> UIFont {
if let cached = fontCache[weigth]?[size] {
return cached
}
let descriptor = AppFont.fontDescriptor(family: "SF Compact Display", size: size, weight: weigth)
let font = UIFont(descriptor: descriptor, size: size)
if fontCache[weigth] == nil {
fontCache[weigth] = [size: font]
}
else {
fontCache[weigth]![size] = font
}
return font
}
static func light(size: CGFloat) -> UIFont {
font(weigth: .light, size: size)
}
static func regular(size: CGFloat) -> UIFont {
font(weigth: .regular, size: size)
}
static func semibold(size: CGFloat) -> UIFont {
font(weigth: .semibold, size: size)
}
}
}
......@@ -165,7 +165,6 @@ class ForecastTimePeriodView: UIView {
}
private func updateGraphLayout() {
print("[ForecastTimePeriod] Update graph layout")
graphRect = (stackView.arrangedSubviews.first as? PeriodButtonProtocol)?.graphRect ?? .zero
graphView.frame = .init(x: 0,
y: graphRect.origin.y,
......@@ -299,8 +298,6 @@ class ForecastTimePeriodView: UIView {
self.graphView.drawAdditionalGraph(with: [CGPoint]())
self.tintGraphAt(button: selectedButton)
}
print("[ForecastTimePeriod] Draw graph")
}
private func tintGraphAt(button:PeriodButtonProtocol) {
......
......@@ -115,4 +115,9 @@ struct DefaultTheme: ThemeProtocol {
var mapControlsColor: UIColor {
return UIColor(named: "map_controls_color") ?? .red
}
//Ads
var nativeAdCallToActionColor: UIColor {
return UIColor(named: "native_ad_call_to_action_background") ?? .red
}
}
......@@ -49,4 +49,7 @@ public protocol ThemeProtocol {
//Map
var mapControlsColor:UIColor { get }
//Ads
var nativeAdCallToActionColor: UIColor { get }
}
//
// TodayAdCell.swift
// 1Weather
//
// Created by Dmitry Stepanets on 12.02.2021.
//
import UIKit
protocol AdCell {
var adView: AdView? { get set }
}
//
// TodayAdCell.swift
// BannerAdCell.swift
// 1Weather
//
// Created by Dmitry Stepanets on 12.02.2021.
......@@ -7,7 +7,8 @@
import UIKit
class AdCell: UITableViewCell {
class BannerAdCell: UITableViewCell, AdCell {
//Private
private let container = UIView()
private let label = UILabel()
......@@ -60,13 +61,15 @@ class AdCell: UITableViewCell {
}
//MARK:- Prepare
private extension AdCell {
private extension BannerAdCell {
func prepareCellStyle() {
selectionStyle = .none
clipsToBounds = true
}
func prepareContainer() {
container.layer.cornerRadius = 6
container.clipsToBounds = true
contentView.addSubview(container)
container.snp.makeConstraints { (make) in
......@@ -82,7 +85,7 @@ private extension AdCell {
subview.removeFromSuperview()
}
label.text = "Advertisment"
label.text = "ads.placeholder".localized()
label.font = AppFont.SFPro.regular(size: 14)
container.addSubview(label)
......
//
// MRECAdCell.swift
// 1Weather
//
// Created by Demid Merzlyakov on 08.06.2021.
//
import UIKit
class MRECAdCell: UITableViewCell, AdCell {
//Private
private let container = UIView()
private let label = UILabel()
public var adView: AdView? = nil {
didSet {
guard adView != oldValue else {
return
}
prepareAd()
}
}
private let gradientView = GradientView(startColor: UIColor.white.withAlphaComponent(0),
endColor: UIColor(hex: 0xdaddec),
opacity: 0.5)
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
prepareCell()
prepareContainer()
prepareAd()
prepareGradient()
updateUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateUI()
}
private func updateUI() {
contentView.backgroundColor = ThemeManager.currentTheme.baseBackgroundColor
container.backgroundColor = ThemeManager.currentTheme.containerBackgroundColor
label.textColor = ThemeManager.currentTheme.secondaryTextColor
switch interfaceStyle {
case .light:
gradientView.isHidden = false
case .dark:
gradientView.isHidden = true
}
}
}
//MARK:- Prepare
private extension MRECAdCell {
func prepareCell() {
selectionStyle = .none
clipsToBounds = true
}
func prepareContainer() {
label.text = "ads.placeholder".localized()
label.font = AppFont.SFPro.regular(size: 10)
label.textColor = ThemeManager.currentTheme.secondaryTextColor
contentView.addSubview(label)
contentView.addSubview(container)
label.snp.makeConstraints { make in
make.top.equalToSuperview().inset(18)
make.trailing.equalTo(container.snp.trailing)
}
container.snp.makeConstraints { (make) in
make.top.equalTo(label.snp.bottom).offset(6)
make.height.equalTo(250)
make.bottom.equalToSuperview().inset(18)
make.centerX.equalToSuperview()
make.width.greaterThanOrEqualTo(300)
}
}
func prepareAd() {
for subview in container.subviews {
subview.removeFromSuperview()
}
if let adView = adView {
container.addSubview(adView)
adView.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.size.equalToSuperview()
}
}
}
func prepareGradient() {
contentView.addSubview(gradientView)
contentView.bringSubviewToFront(container)
gradientView.snp.makeConstraints { (make) in
make.left.bottom.right.equalToSuperview()
make.height.equalToSuperview().multipliedBy(0.5)
}
}
}
......@@ -31,6 +31,7 @@ class ForecastViewController: UIViewController {
self.coordinator = coordinator
self.forecastCellFactory = ForecastCellFactory(viewModel: viewModel)
super.init(nibName: nil, bundle: nil)
self.forecastCellFactory.delegate = self
}
required init?(coder: NSCoder) {
......@@ -160,7 +161,6 @@ private extension ForecastViewController {
tableView.separatorStyle = .none
tableView.tableFooterView = UIView()
tableView.estimatedRowHeight = UITableView.automaticDimension
tableView.rowHeight = UITableView.automaticDimension
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
......@@ -248,6 +248,10 @@ extension ForecastViewController: UITableViewDataSource {
return forecastCellFactory.cellFromTableView(tableView: tableView,
indexPath: indexPath)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
forecastCellFactory.height(for: indexPath)
}
}
//MARK:- ViewModel Delegate
......@@ -279,3 +283,9 @@ extension ForecastViewController: DaysControlViewDelegate {
viewModel.offsetHolder.update(offset: offset)
}
}
extension ForecastViewController: CellFactoryDelegate {
func cellFactoryCellsChanged(_ factory: CellFactory) {
self.tableView.reloadData()
}
}
......@@ -8,7 +8,7 @@
import UIKit
import OneWeatherCore
class LocationCellFactory: CellFactoryProtocol {
class LocationCellFactory: CellFactory {
//Private
private let locationsViewModel:LocationsViewModel
......
......@@ -91,7 +91,7 @@ private struct SectionItem {
let rows:[MenuRow]
}
class MenuCellFactory<T>: CellFactoryProtocol {
class MenuCellFactory<T>: CellFactory {
//Private
private let menuViewModel:MenuViewModel
private let sections:[SectionItem] = [SectionItem(type: .info, rows: [.settings]),
......
......@@ -12,7 +12,8 @@ fileprivate enum NWSAlertCellType: Int {
case header = 0
case forecastOffice
case extendedInfoBlock
case ad
case adBanner
case adMREC
}
fileprivate protocol NWSAlertTableViewSection {
......@@ -31,9 +32,17 @@ fileprivate struct HeaderSection: NWSAlertTableViewSection {
//do nothing
}
private let rows: [NWSAlertCellType] = [.header, .forecastOffice]
private let rows: [NWSAlertCellType] = {
if !isAppPro() && AdConfigManager.shared.adConfig.adsEnabled {
return [.header, .forecastOffice, .adBanner]
}
else {
return [.header, .forecastOffice]
}
}()
var numberOfRows: Int {
return rows.count
rows.count
}
func type(forRow row: Int) -> NWSAlertCellType {
......@@ -43,19 +52,13 @@ fileprivate struct HeaderSection: NWSAlertTableViewSection {
fileprivate struct ExtendedInfoSection: NWSAlertTableViewSection {
private var alert: NWSAlert
private var countOfAds: Int {
if !isAppPro() && AdConfigManager.shared.adConfig.adsEnabled {
return 1
}
return 0
}
init(alert: NWSAlert) {
self.alert = alert
}
var numberOfRows: Int {
countOfAds + (alert.extendedInfo?.infoBlocks.count ?? 0)
alert.extendedInfo?.infoBlocks.count ?? 0
}
mutating func update(with alert: NWSAlert) {
......@@ -63,29 +66,19 @@ fileprivate struct ExtendedInfoSection: NWSAlertTableViewSection {
}
func type(forRow row: Int) -> NWSAlertCellType {
guard countOfAds > 0 else {
return .extendedInfoBlock
}
if numberOfRows == 1 {
return .ad
}
else {
if row == 1 {
return .ad
}
else {
return .extendedInfoBlock
}
}
.extendedInfoBlock
}
let rows: [NWSAlertCellType] = [.extendedInfoBlock]
}
class NWSAlertCellFactory: CellFactoryProtocol {
var alert: NWSAlert {
class NWSAlertCellFactory: CellFactory {
fileprivate var sections: [NWSAlertTableViewSection]
private var adViewCache = [IndexPath: AdView]()
public var delegate: CellFactoryDelegate?
public var alert: NWSAlert {
didSet {
for i in 0..<sections.count {
sections[i].update(with: alert)
......@@ -93,19 +86,28 @@ class NWSAlertCellFactory: CellFactoryProtocol {
}
}
init(alert: NWSAlert) {
public init(alert: NWSAlert) {
self.alert = alert
self.sections = [HeaderSection(alert: alert), ExtendedInfoSection(alert: alert)]
}
fileprivate var sections: [NWSAlertTableViewSection]
private var adViewCache = [IndexPath: AdView]()
public func height(for indexPath: IndexPath) -> CGFloat {
let cellType = cellType(at: indexPath)
switch cellType {
case .adBanner: fallthrough
case .adMREC:
let adView = adView(for: indexPath)
return adView.adReady ? UITableView.automaticDimension : 0
default:
return UITableView.automaticDimension
}
}
var numberOfSections: Int {
public var numberOfSections: Int {
return sections.count
}
func numberOfRows(inSection section: Int) -> Int {
public func numberOfRows(inSection section: Int) -> Int {
sections[section].numberOfRows
}
......@@ -114,8 +116,9 @@ class NWSAlertCellFactory: CellFactoryProtocol {
return adView
}
let adView = adViewCache[indexPath] ?? AdView()
adView.delegate = self
adView.loggingAlias = "⚠️ Alert Banner"
adView.set(placementName: placementNamePrecipitationBanner, adType: .banner)
adView.set(placementName: placementNameNWSAlertBanner, adType: .banner)
adViewCache[indexPath] = adView
return adView
}
......@@ -124,12 +127,18 @@ class NWSAlertCellFactory: CellFactoryProtocol {
registerCell(type: NWSAlertCell.self, tableView: tableView)
registerCell(type: NWSForecastOfficeTableViewCell.self, tableView: tableView)
registerCell(type: NWSAlertInfoBlockTableViewCell.self, tableView: tableView)
registerCell(type: AdCell.self, tableView: tableView)
registerCell(type: BannerAdCell.self, tableView: tableView)
registerCell(type: MRECAdCell.self, tableView: tableView)
}
func cellFromTableView(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
private func cellType(at indexPath: IndexPath) -> NWSAlertCellType {
let section = sections[indexPath.section]
let type = section.type(forRow: indexPath.row)
return type
}
public func cellFromTableView(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
let type = cellType(at: indexPath)
switch type {
case .header:
let alertCell = dequeueReusableCell(type: NWSAlertCell.self, tableView: tableView, indexPath: indexPath)
......@@ -147,10 +156,14 @@ class NWSAlertCellFactory: CellFactoryProtocol {
let extendedInfoBlockCell = dequeueReusableCell(type: NWSAlertInfoBlockTableViewCell.self, tableView: tableView, indexPath: indexPath)
extendedInfoBlockCell.configure(with: info)
return extendedInfoBlockCell
case .ad:
let adCell = dequeueReusableCell(type: AdCell.self, tableView: tableView, indexPath: indexPath)
adCell.adView = adView(for: indexPath)
return adCell
case .adBanner:
let cell = dequeueReusableCell(type: BannerAdCell.self, tableView: tableView, indexPath: indexPath)
cell.adView = adView(for: indexPath)
return cell
case .adMREC:
let cell = dequeueReusableCell(type: MRECAdCell.self, tableView: tableView, indexPath: indexPath)
cell.adView = adView(for: indexPath)
return cell
}
}
......@@ -172,3 +185,22 @@ class NWSAlertCellFactory: CellFactoryProtocol {
}
}
}
// MARK: - AdViewDelegate
extension NWSAlertCellFactory: AdViewDelegate {
func succeeded(adView: AdView, hadAdBefore: Bool) {
onMain {
if hadAdBefore != adView.adReady {
self.delegate?.cellFactoryCellsChanged(self)
}
}
}
func failed(adView: AdView, hadAdBefore: Bool) {
onMain {
if hadAdBefore != adView.adReady {
self.delegate?.cellFactoryCellsChanged(self)
}
}
}
}
......@@ -110,7 +110,7 @@ extension NWSAlertViewController: UITableViewDelegate, UITableViewDataSource {
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
UITableView.automaticDimension
return viewModel.cellFactory.height(for: indexPath)
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
......
......@@ -18,7 +18,7 @@ private struct LayerSection {
let rowsCount:Int
}
class RadarLayersCellFactory: CellFactoryProtocol {
class RadarLayersCellFactory: CellFactory {
//Private
private let radarViewModel:RadarViewModel
private let sections:[LayerSection]
......
......@@ -84,7 +84,7 @@ private struct SettingsDataSource {
let rows:[SettingsRow]
}
class SettingsCellFactory: CellFactoryProtocol {
class SettingsCellFactory: CellFactory {
//Private
private let viewModel: SettingsViewModel
private let sections: [SettingsDataSource] = {
......
......@@ -9,7 +9,7 @@ import UIKit
import Localize_Swift
import OneWeatherCore
class SettingsDetailsCellFactory: CellFactoryProtocol {
class SettingsDetailsCellFactory: CellFactory {
//Private
private let viewModel:SettingsDetailsViewModel
......
......@@ -11,7 +11,8 @@ import OneWeatherCore
public enum TodayCellType:Int {
case alert = 0
case forecast
case ad
case adBanner
case adMREC
case conditions
case forecastPeriod
case precipitation
......@@ -49,18 +50,19 @@ private struct TodaySection {
}
}
class TodayCellFactory: CellFactoryProtocol {
class TodayCellFactory: CellFactory {
//Private
private var cellsToUpdate:CellsToUpdate = [.condition, .timePeriod, .precipitation, .dayTime]
private let todayViewModel:TodayViewModel
private var todaySection = TodaySection(allRows: [.alert, .forecast, .ad,
.conditions, .forecastPeriod, .precipitation,
private var todaySection = TodaySection(allRows: [.alert, .forecast, .adBanner,
.conditions, .forecastPeriod, .precipitation, .adMREC,
.airQuality, .dayTime, .sun, .moon])
private var adViewCache = [IndexPath: AdView]()
//Public
public var delegate: CellFactoryDelegate?
init(viewModel: TodayViewModel) {
self.todayViewModel = viewModel
}
......@@ -76,7 +78,8 @@ class TodayCellFactory: CellFactoryProtocol {
public func registerCells(on tableView:UITableView) {
registerCell(type: TodayAlertCell.self, tableView: tableView)
registerCell(type: TodayForecastCell.self, tableView: tableView)
registerCell(type: AdCell.self, tableView: tableView)
registerCell(type: BannerAdCell.self, tableView: tableView)
registerCell(type: MRECAdCell.self, tableView: tableView)
registerCell(type: TodayConditionsCell.self, tableView: tableView)
registerCell(type: TodayForecastTimePeriodCell.self, tableView: tableView)
registerCell(type: PrecipitationCell.self, tableView: tableView)
......@@ -90,9 +93,15 @@ class TodayCellFactory: CellFactoryProtocol {
if let adView = adViewCache[indexPath] {
return adView
}
let adView = adViewCache[indexPath] ?? AdView()
let adView = AdView()
adView.delegate = self
adView.loggingAlias = "📍 Today Banner"
adView.set(placementName: placementNameTodayBanner, adType: .banner)
var adType = AdType.banner
if cellType(at: indexPath) == .adMREC {
adType = .square
adView.loggingAlias = "📅 Today MREC"
}
adView.set(placementName: placementNameTodayBanner, adType: adType)
adViewCache[indexPath] = adView
return adView
}
......@@ -117,16 +126,17 @@ class TodayCellFactory: CellFactoryProtocol {
let cell = dequeueReusableCell(type: TodayForecastCell.self, tableView: tableView, indexPath: indexPath)
cell.configure(with: loc)
return cell
case .ad:
let cell = dequeueReusableCell(type: AdCell.self, tableView: tableView, indexPath: indexPath)
case .adBanner:
let cell = dequeueReusableCell(type: BannerAdCell.self, tableView: tableView, indexPath: indexPath)
cell.adView = adView(for: indexPath)
return cell
case .adMREC:
let cell = dequeueReusableCell(type: MRECAdCell.self, tableView: tableView, indexPath: indexPath)
cell.adView = adView(for: indexPath)
return cell
case .conditions:
let cell = dequeueReusableCell(type: TodayConditionsCell.self, tableView: tableView, indexPath: indexPath)
// if cellsToUpdate.contains(.condition) {
cell.configure(with: loc)
// cellsToUpdate.remove(.condition)
// }
return cell
case .forecastPeriod:
let cell = dequeueReusableCell(type: TodayForecastTimePeriodCell.self, tableView: tableView, indexPath: indexPath)
......@@ -164,6 +174,18 @@ class TodayCellFactory: CellFactoryProtocol {
}
}
public func height(for indexPath: IndexPath) -> CGFloat {
let cellType = cellType(at: indexPath)
switch cellType {
case .adBanner: fallthrough
case .adMREC:
let adView = adView(for: indexPath)
return adView.adReady ? UITableView.automaticDimension : 0
default:
return UITableView.automaticDimension
}
}
public func setNeedsUpdate() {
cellsToUpdate = [.condition, .timePeriod, .precipitation, .dayTime]
setupHiddenRows()
......@@ -195,7 +217,8 @@ class TodayCellFactory: CellFactoryProtocol {
var rowsToHide = Set<TodayCellType>()
if isAppPro() || !AdConfigManager.shared.adConfig.adsEnabled {
rowsToHide.insert(.ad)
rowsToHide.insert(.adBanner)
rowsToHide.insert(.adMREC)
}
let location = self.todayViewModel.location
......@@ -214,3 +237,22 @@ class TodayCellFactory: CellFactoryProtocol {
todaySection.hiddenRows = rowsToHide
}
}
// MARK: - AdViewDelegate
extension TodayCellFactory: AdViewDelegate {
func succeeded(adView: AdView, hadAdBefore: Bool) {
onMain {
if hadAdBefore != adView.adReady {
self.delegate?.cellFactoryCellsChanged(self)
}
}
}
func failed(adView: AdView, hadAdBefore: Bool) {
onMain {
if hadAdBefore != adView.adReady {
self.delegate?.cellFactoryCellsChanged(self)
}
}
}
}
......@@ -107,7 +107,6 @@ private extension TodayViewController {
tableView.separatorStyle = .none
tableView.tableFooterView = UIView()
tableView.estimatedRowHeight = UITableView.automaticDimension
tableView.rowHeight = UITableView.automaticDimension
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
......@@ -127,6 +126,10 @@ extension TodayViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return viewModel.todayCellFactory.cellFromTableView(tableView: tableView, indexPath: indexPath)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return viewModel.todayCellFactory.height(for: indexPath)
}
}
//MARK:- UITableView Delegate
......
......@@ -25,6 +25,7 @@ class NWSAlertViewModel: ViewModelProtocol {
cellFactory = NWSAlertCellFactory(alert: alert)
alertsManager.delegates.add(delegate: self)
NotificationCenter.default.addObserver(self, selector: #selector(handlePremiumStateChange), name: Notification.Name(rawValue: kEventInAppPurchasedCompleted), object: nil)
cellFactory.delegate = self
}
@objc
......@@ -35,6 +36,7 @@ class NWSAlertViewModel: ViewModelProtocol {
}
}
//MARK: - NWSAlertsManagerDelegate
extension NWSAlertViewModel: NWSAlertsManagerDelegate {
func alertsListDidChange(in alertsManager: NWSAlertsManager) {
// do nothing
......@@ -48,3 +50,10 @@ extension NWSAlertViewModel: NWSAlertsManagerDelegate {
}
}
}
extension NWSAlertViewModel: CellFactoryDelegate {
func cellFactoryCellsChanged(_ factory: CellFactory) {
delegate?.viewModelDidChange(model: self)
}
}
......@@ -24,7 +24,9 @@ class TodayViewModel: ViewModelProtocol {
private(set) var location:Location?
public lazy var todayCellFactory:TodayCellFactory = {
TodayCellFactory(viewModel: self)
let factory = TodayCellFactory(viewModel: self)
factory.delegate = self
return factory
}()
deinit {
......@@ -130,3 +132,10 @@ extension TodayViewModel: SettingsDelegate {
delegate?.viewModelDidChange(model: self)
}
}
// MARK: CellFactoryDelegate
extension TodayViewModel: CellFactoryDelegate {
func cellFactoryCellsChanged(_ factory: CellFactory) {
delegate?.viewModelDidChange(model: self)
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment