//
// GameVC.swift
// EmojiPuzzle
//
// Created by iMac on 01/10/22.
//
import UIKit
import GoogleMobileAds
class GameVC: UIViewController {
//MARK: - Properties -
// Type 0
@IBOutlet weak var bottomConstant: NSLayoutConstraint!
@IBOutlet weak var lblLevelCount: UILabel!
@IBOutlet var rightLabel1: PaddingLabel!
@IBOutlet var rightLabel2: PaddingLabel!
@IBOutlet var rightLabel3: PaddingLabel!
@IBOutlet var rightLabel4: PaddingLabel!
@IBOutlet var leftLabel1: PaddingLabel!
@IBOutlet var leftLabel2: PaddingLabel!
@IBOutlet var leftLabel3: PaddingLabel!
@IBOutlet var leftLabel4: PaddingLabel!
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet var rightStackView: UIStackView!
@IBOutlet var leftStackView: UIStackView!
@IBOutlet var leftRightViews: UIView!
@IBOutlet var middleLevelViews: UIView!
// Type 1
@IBOutlet weak var collectionView: UICollectionView! {
didSet {
collectionView.delegate = self
collectionView.dataSource = self
collectionView.dropDelegate = self
}
}
@IBOutlet weak var collectionView2: UICollectionView!{
didSet {
collectionView2.delegate = self
collectionView2.dataSource = self
collectionView2.dragDelegate = self
}
}
@IBOutlet var dragViews: [UIView]!
private lazy var lineShape: CAShapeLayer = {
let lineShape = CAShapeLayer()
lineShape×strokeColor = UIColor.green.cgColor
lineShape×fillColor = UIColor.green.cgColor
lineShape.lineWidth = 2.0
return lineShape
}()
private var panGestureStartPoint: CGPoint = .zero
private lazy var leftPanRecognizer1: UIPanGestureRecognizer = {
return UIPanGestureRecognizer(target: self,
action: #selector(leftPanGestureCalled(_:)))
}()
private lazy var leftPanRecognizer2: UIPanGestureRecognizer = {
return UIPanGestureRecognizer(target: self,
action: #selector(leftPanGestureCalled(_:)))
}()
private lazy var leftPanRecognizer3: UIPanGestureRecognizer = {
return UIPanGestureRecognizer(target: self,
action: #selector(leftPanGestureCalled(_:)))
}()
private lazy var leftPanRecognizer4: UIPanGestureRecognizer = {
return UIPanGestureRecognizer(target: self,
action: #selector(leftPanGestureCalled(_:)))
}()
var imageArray: [UIImage?] = [
UIImage(named: "bg1"),
UIImage(named: "bg5"),
UIImage(named: "bg7"),
UIImage(named: "bg8"),
UIImage(named: "bg9"),
UIImage(named: "bg11")
]
var adBannerView: GADBannerView?
var selectedView = [String: String]()
var correctAnswerArray = [String: String]()
var connectionLines = [CAShapeLayer]()
var selectedIndex = AppManager.shared.selectedLevel
var leftViews:[UILabel] = []
var rightViews:[UILabel] = []
var questions:[String] = []
var answers:[String] = []
var originalQuesArray:[String] = []
var originalAnsArray:[String] = []
var isCountFour = false
var levelPassed: [Bool] = []
//MARK: - Life Cycle Functions -
override func viewDidLoad() {
super.viewDidLoad()
adBannerView = GADBannerView(adSize:
kGADAdSizeSmartBannerLandscape)
initAdMobBanner()
changeBackgroundImages()
self.panGestureStartPoint = (leftStackView.convert(leftLabel1.center,
to: self.view))
self.leftLabel1.addGestureRecognizer(leftPanRecognizer1)
self.leftLabel2.addGestureRecognizer(leftPanRecognizer2)
self.leftLabel3.addGestureRecognizer(leftPanRecognizer3)
self.leftLabel4.addGestureRecognizer(leftPanRecognizer4)
self.viewManageForLevel()
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?)
{
for (index,labelPoint) in leftViews.enumerated() {
if !((selectedView["left\(index+1)"]?.contains("right") ?? false)
|| selectedView["left\(index+1)"] == "0") {
labelPoint.layer.borderWidth = 0
labelPoint.layer.borderColor = UIColor.clear.cgColor
}
}
}
//MARK: - Selectors -
@IBAction func backButtonAction(_ sender: UIButton) {
self.view.endEditing(true)
myApp.addEventCount(gViewController: self)
self.navigationController?.popViewController(animated: true)
}
@IBAction func reloadButtonAction(_ sender: UIButton) {
self.view.endEditing(true)
}
@IBAction func settingsButtonAction(_ sender: UIButton) {
self.view.endEditing(true)
myApp.addEventCount(gViewController: self)
let newVC = self.storyboard?.instantiateViewController(withIdentifier:
"SettingAlertVC") as! SettingAlertVC
newVC.delegate = self
newVC.view.backgroundColor = UIColor(white: 0,
alpha: 0.5)
self.definesPresentationContext = true
self.providesPresentationContextTransitionStyle = true
newVC.modalPresentationStyle = .overFullScreen
self.present(newVC, animated: true, completion: nil)
}
@objc func leftPanGestureCalled(_ panRecognizer:
UIPanGestureRecognizer) {
let currentPanPoint = panRecognizer×location(in: self.view)
switch panRecognizer.state {
case .began:
self.panGestureBegan(panRecognizer,
currentPanPoint)
case .changed:
self.panGestureChanged(panRecognizer,
currentPanPoint)
case .ended:
self.panGestureEnded(panRecognizer)
default:
break
}
}
}
//MARK: - Helper Funtions -
extension GameVC {
// Change Background Images
func changeBackgroundImages() {
DispatchQueue.main.async {
if let image = self×imageArray×randomElement() {
self×backgroundImageView×image = image
}
}
}
// Pan Gesture Began
func panGestureBegan(_ panRecognizer: UIPanGestureRecognizer,
_ currentPanPoint: CGPoint) {
var newIndex = 0
for (index,labelPoint) in leftViews.enumerated() {
let point = panRecognizer.location(in: labelPoint)
if labelPoint.layer.contains(point){
labelPoint.layer.cornerRadius = 10
labelPoint.layer.borderWidth = 3
labelPoint.layer.borderColor = UIColor.green.cgColor
panGestureStartPoint = currentPanPoint
if selectedView["left\(index+1)"] == "" {
selectedView["left\(index+1)"] = "0"
}else{
newIndex = index+1
}
}
}
for (index,labelPoint) in leftViews.enumerated() {
if !((selectedView["left\(index+1)"]?.contains("right") ?? false) ||
selectedView["left\(index+1)"] == "0") {
labelPoint.layer.borderWidth = 0
labelPoint.layer.borderColor = UIColor.clear.cgColor
}else {
let newKeyValue = selectedView["left\(newIndex)"]
for line in connectionLines {
if line.accessibilityValue == "left\(newIndex)" {
if line.accessibilityLabel == newKeyValue {
selectedView["left\(newIndex)"] = "0"
line.removeFromSuperlayer()
}
}
}
}
}
self.view.layer.addSublayer(lineShape)
}
// Pan Gesture Changed
func panGestureChanged(_ panRecognizer: UIPanGestureRecognizer,
_ currentPanPoint: CGPoint) {
let linePath = UIBezierPath()
linePath.move(to: panGestureStartPoint)
linePath.addLine(to: currentPanPoint)
lineShape×path = CGPath.barbell(from: panGestureStartPoint,
to: currentPanPoint,
barThickness: 1.0,
bellRadius: 3.0)
for (indx,labelPoint) in rightViews.enumerated() {
let point = panRecognizer.location(in: labelPoint)
if labelPoint.layer.contains(point){
lineShape×path = CGPath.barbell(from: panGestureStartPoint,
to: rightStackView.convert(labelPoint.center,
to: self.view),
barThickness: 1.0,
bellRadius: 3.0)
labelPoint.layer.borderWidth = 3
labelPoint.layer.borderColor = UIColor.green.cgColor
} else {
if !(selectedView.values.contains("right\(indx+1)")) {
labelPoint.layer.borderWidth = 0
labelPoint.layer.borderColor = UIColor.clear.cgColor
}
}
}
}
// Pan Gesture Ended
func panGestureEnded(_ panRecognizer: UIPanGestureRecognizer){
var isViewAdded = false
var newIndex = 0
for (indx,labelPoint) in rightViews.enumerated() {
let point = panRecognizer.location(in: labelPoint)
if labelPoint.layer.contains(point) {
labelPoint.layer.borderWidth = 3
labelPoint.layer.borderColor = UIColor.green.cgColor
isViewAdded = true
// green
for (index, label) in leftViews.enumerated() {
if (selectedView["left\(index+1)"] == "0") {
newIndex = index+1
selectedView["left\(index+1)"] = "right\(indx+1)"
addLine(fromPoint: leftStackView.convert(label.center, to:
self.view), toPoint: rightStackView.convert(labelPoint.center, to: self.view),
color: .green, value: "right\(indx+1)", value2: "left\(index+1)")
}
}
lineShape×path = nil
lineShape.removeFromSuperlayer()
}
}
if !isViewAdded {
lineShape×path = nil
lineShape.removeFromSuperlayer()
for (index, _) in leftViews.enumerated() {
if (selectedView["left\(index+1)"] == "0") {
selectedView["left\(index+1)"] = ""
}
}
} else {
let newKeyValue = selectedView["left\(newIndex)"]
for (_,item) in selectedView.keys.enumerated() {
if "left\(newIndex)" != item {
if (newKeyValue == selectedView[item]) {
selectedView[item] = ""
for line in connectionLines {
if line.accessibilityValue != "left\(newIndex)" {
if line.accessibilityLabel == newKeyValue {
line.removeFromSuperlayer()
}
}
}
}
}
}
for (index,labelPoint) in leftViews.enumerated() {
if !((selectedView["left\(index+1)"]?.contains("right") ?? false)
|| selectedView["left\(index+1)"] == "0") {
labelPoint.layer.borderWidth = 0
labelPoint.layer.borderColor = UIColor.clear.cgColor
}
}
}
var isGameFinish = true
for i in selectedView {
if i.value == "" {
isGameFinish = false
}
}
if isGameFinish {
for correct in correctAnswerArray {
levelPassed.append(selectedView[correct.key] == correct.value)
if !(selectedView[correct.key] == correct.value) {
for line in connectionLines {
if line.accessibilityLabel == selectedView[correct.key] &&
line.accessibilityValue == correct.key {
line.strokeColor = UIColor.red.cgColor
line.fillColor = UIColor.red.cgColor
}
}
}
}
self.view.endEditing(true)
let newVC = self.storyboard?.instantiateViewController(withIdentifier:
"SuccessAlertVC") as! SuccessAlertVC
newVC.isPassed = !levelPassed.contains(false)
newVC.delegate = self
newVC.view.backgroundColor = UIColor(white: 0,
alpha: 0.5)
self.definesPresentationContext = true
self.providesPresentationContextTransitionStyle = true
newVC.modalPresentationStyle = .overFullScreen
DispatchQueue.main.async {
self.present(newVC,
animated: true,
completion: nil)
}
}
}
func levelSuccessAndFailed(count: Int) {
myApp.addEventCount(gViewController: self)
for item in connectionLines {
for (i,_) in questions.enumerated() {
if item.accessibilityValue == "left\(i+1)" {
item.removeFromSuperlayer()
}
}
}
isCountFour = false
self.selectedView.removeAll()
correctAnswerArray.removeAll()
leftViews.removeAll()
rightViews.removeAll()
questions.removeAll()
answers.removeAll()
originalQuesArray.removeAll()
originalAnsArray.removeAll()
rightLabel1.layer×borderColor = UIColor.clear.cgColor
rightLabel2.layer×borderColor = UIColor.clear.cgColor
rightLabel3.layer×borderColor = UIColor.clear.cgColor
rightLabel4.layer×borderColor = UIColor.clear.cgColor
leftLabel1.layer×borderColor = UIColor.clear.cgColor
leftLabel2.layer×borderColor = UIColor.clear.cgColor
leftLabel3.layer×borderColor = UIColor.clear.cgColor
leftLabel4.layer×borderColor = UIColor.clear.cgColor
self.selectedIndex = count
self.viewManageForLevel()
}
// Add Line
func addLine(fromPoint start: CGPoint,
toPoint end:CGPoint,
color: UIColor,
value: String,
value2: String) {
let line = CAShapeLayer()
let linePath = UIBezierPath()
linePath.move(to: start)
linePath.addLine(to: end)
line×strokeColor = color.cgColor
line×fillColor = color.cgColor
line×path = CGPath.barbell(from: start, to: end, barThickness: 1.0,
bellRadius: 3.0)
line.lineWidth = 2.0
line×accessibilityLabel = value
line×accessibilityValue = value2
connectionLines.append(line)
self.view.layer.addSublayer(line)
}
// Game View Manages
func viewManageForLevel() {
myApp.addEventCount(gViewController: self)
lblLevelCount.text = "Level \(selectedIndex+1)"
leftRightViews.isHidden = gameData[selectedIndex].levelType != "0"
middleLevelViews.isHidden = gameData[selectedIndex].levelType == "0"
for i in dragViews {
i.layer.borderColor = UIColor.yellow.cgColor
}
originalAnsArray = gameData[selectedIndex].answer
originalQuesArray = gameData[selectedIndex].question
if gameData[selectedIndex].levelType == "0" {
if gameData[selectedIndex].question.count == 2 {
rightLabel1.isHidden = false
rightLabel2.isHidden = false
rightLabel3.isHidden = true
rightLabel4.isHidden = true
leftLabel1.isHidden = false
leftLabel2.isHidden = false
leftLabel3.isHidden = true
leftLabel4.isHidden = true
leftViews = [leftLabel1, leftLabel2]
rightViews = [rightLabel1, rightLabel2]
questions = gameData[selectedIndex].question
answers = gameData[selectedIndex].answer.reversed().shuffled()
leftLabel1.text = questions[0]
leftLabel2.text = questions[1]
rightLabel1.text = answers[0]
rightLabel2.text = answers[1]
for (index, _) in leftViews.enumerated() {
selectedView["left\(index+1)"] = ""
}
for (index, item) in originalAnsArray.enumerated() {
for (index2,ans) in answers.enumerated() {
if item == ans {
correctAnswerArray["left\(index+1)"] = "right\(index2+1)"
}
}
}
}
else if gameData[selectedIndex].question.count == 3 {
rightLabel1.isHidden = false
rightLabel2.isHidden = false
rightLabel3.isHidden = false
rightLabel4.isHidden = true
leftLabel1.isHidden = false
leftLabel2.isHidden = false
leftLabel3.isHidden = false
leftLabel4.isHidden = true
leftViews = [leftLabel1, leftLabel2, leftLabel3]
rightViews = [rightLabel1, rightLabel2, rightLabel3]
questions = gameData[selectedIndex].question
answers = gameData[selectedIndex].answer.shuffled()
leftLabel1.text = questions[0]
leftLabel2.text = questions[1]
leftLabel3.text = questions[2]
rightLabel1.text = answers[0]
rightLabel2.text = answers[1]
rightLabel3.text = answers[2]
for (index, _) in leftViews.enumerated() {
selectedView["left\(index+1)"] = ""
}
for (index, item) in originalAnsArray.enumerated() {
for (index2,ans) in answers.enumerated() {
if item == ans {
correctAnswerArray["left\(index+1)"] = "right\(index2+1)"
}
}
}
}
else if gameData[selectedIndex].question.count == 4 {
rightLabel1.isHidden = false
rightLabel2.isHidden = false
rightLabel3.isHidden = false
rightLabel4.isHidden = false
leftLabel1.isHidden = false
leftLabel2.isHidden = false
leftLabel3.isHidden = false
leftLabel4.isHidden = false
leftViews = [leftLabel1, leftLabel2, leftLabel3, leftLabel4]
rightViews = [rightLabel1, rightLabel2, rightLabel3, rightLabel4]
questions = gameData[selectedIndex].question
answers = gameData[selectedIndex].answer.reversed().shuffled()
leftLabel1.text = questions[0]
leftLabel2.text = questions[1]
leftLabel3.text = questions[2]
leftLabel4.text = questions[3]
rightLabel1.text = answers[0]
rightLabel2.text = answers[1]
rightLabel3.text = answers[2]
rightLabel4.text = answers[3]
for (index, _) in leftViews.enumerated() {
selectedView["left\(index+1)"] = ""
}
for (index, item) in originalAnsArray.enumerated() {
for (index2,ans) in answers.enumerated() {
if item == ans {
correctAnswerArray["left\(index+1)"] = "right\(index2+1)"
}
}
}
} else {
rightLabel1.isHidden = false
rightLabel2.isHidden = true
rightLabel3.isHidden = true
rightLabel4.isHidden = true
leftLabel1.isHidden = false
leftLabel2.isHidden = true
leftLabel3.isHidden = true
leftLabel4.isHidden = true
leftViews = [leftLabel1]
rightViews = [rightLabel1]
questions = gameData[selectedIndex].question
answers = gameData[selectedIndex].answer.reversed().shuffled()
leftLabel1.text = questions[0]
rightLabel1.text = answers[0]
for (index, _) in leftViews.enumerated() {
selectedView["left\(index+1)"] = ""
}
for (index, item) in originalAnsArray.enumerated() {
for (index2,ans) in answers.enumerated() {
if item == ans {
correctAnswerArray["left\(index+1)"] = "right\(index2+1)"
}
}
}
}
} else {
questions = gameData[selectedIndex].question
answers = gameData[selectedIndex].answer.shuffled()
print(questions, answers)
self.collectionView.reloadData()
self.collectionView2.reloadData()
}
}
}
//MARK: - Extensions -
extension GameVC: SettingAlertProtocol {
func view(_ vc: SettingAlertVC, didTapPrivacyPolicyButtonAt sender:
UIButton) {
self.view.endEditing(true)
myApp.addEventCount(gViewController: self)
let newVC = self.storyboard?.instantiateViewController(withIdentifier:
"PrivacyPolicyVC") as! PrivacyPolicyVC
self.navigationController?.pushViewController(newVC, animated: true)
}
}
extension GameVC: SuccessAlertDelegate {
func view(_ vc: SuccessAlertVC, didTapButtonAt sender: UIButton, isPassed:
Bool) {
vc.dismiss(animated: true, completion: nil)
levelPassed.removeAll()
if isPassed {
let count = self×selectedIndex+1
AppManager.shared.selectedLevel = count
levelSuccessAndFailed(count: count)
} else {
AppManager.shared.selectedLevel = self.selectedIndex
levelSuccessAndFailed(count: self.selectedIndex)
}
}
}
extension GameVC: UICollectionViewDelegate,
UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
if collectionView == self.collectionView {
return questions.count
}
return answers.count
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView×dequeueReusableCell(withReuseIdentifier: "Cell",
for: indexPath) as! LevelCVCell
if collectionView == self.collectionView {
if indexPath.row == (questions.count-1) {
cell×lblStricker×text = nil
}else {
cell×lblStricker×text = questions[indexPath.row]
}
} else {
cell×lblStricker×text = answers[indexPath.row]
}
return cell
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
if collectionView == self.collectionView {
return CGSize(width: collectionView.bounds.width/2, height:
collectionView.bounds.height/2)
}else{
return CGSize(width: collectionView.bounds.width, height:
collectionView.bounds.height/3)
}
}
}
// MARK: - UICollectionViewDragDelegate Methods -
extension GameVC : UICollectionViewDragDelegate {
func collectionView(_ collectionView: UICollectionView, itemsForBeginning
session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
let item = answers[indexPath.row]
let itemProvider = NSItemProvider(object: item as NSString)
let dragItem = UIDragItem(itemProvider: itemProvider)
session.localContext = DragCoordinator(sourceIndexPath: indexPath)
dragItem×localObject = item
return [dragItem]
}
func collectionView(_ collectionView: UICollectionView, itemsForAddingTo
session: UIDragSession, at indexPath: IndexPath, point: CGPoint) ->
[UIDragItem] {
let item = answers[indexPath.row]
let itemProvider = NSItemProvider(object: item as NSString)
let dragItem = UIDragItem(itemProvider: itemProvider)
dragItem×localObject = item
return [dragItem]
}
func collectionView(_ collectionView: UICollectionView,
dragPreviewParametersForItemAt indexPath: IndexPath) ->
UIDragPreviewParameters? {
let previewParameters = UIDragPreviewParameters()
previewParameters×backgroundColor = .clear
return previewParameters
}
func collectionView(_ collectionView: UICollectionView, dragSessionDidEnd
session: UIDragSession) {
guard
let dragCoordinator = session.localContext as? DragCoordinator,
dragCoordinator.dragCompleted == true,
dragCoordinator.isReordering == false
else {
return
}
let sourceIndexPath = dragCoordinator.sourceIndexPath
collectionView.performBatchUpdates({
print("nameCollection Drag:", sourceIndexPath)
})
}
// MARK: - UICollectionViewDropDelegate Methods -
extension GameVC : UICollectionViewDropDelegate {
func collectionView(_ collectionView: UICollectionView, canHandle session:
UIDropSession) -> Bool {
return session.canLoadObjects(ofClass: NSString.self)
}
func collectionView(_ collectionView: UICollectionView,
dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath
destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
if let destinationIndexPath = destinationIndexPath {
if (destinationIndexPath.row) < 3 {
return UICollectionViewDropProposal(operation: .cancel)
}
}
if isCountFour {
return UICollectionViewDropProposal(operation: .cancel)
}
return UICollectionViewDropProposal(
operation: .move,
intent: .insertIntoDestinationIndexPath)
}
func collectionView(_ collectionView: UICollectionView, performDropWith
coordinator: UICollectionViewDropCoordinator) {
let destinationIndexPath: IndexPath
if let indexPath = coordinator×destinationIndexPath
{
destinationIndexPath = indexPath
}
else
{
// Get last index path of table view.
let section = collectionView.numberOfSections - 1
let row = collectionView×numberOfItems(inSection: section)
destinationIndexPath = IndexPath(row: row, section: section)
}
switch coordinator.proposal.operation
{
case .move:
guard let dragCoordinator =
coordinator.session.localDragSession?.localContext as?
DragCoordinator
else { return }
_ = dragCoordinator.sourceIndexPath
self.copyItems(coordinator: coordinator, destinationIndexPath:
destinationIndexPath, collectionView: collectionView)
dragCoordinator.dragCompleted = true
break
case .copy:
self.copyItems(coordinator: coordinator, destinationIndexPath:
destinationIndexPath, collectionView: collectionView)
default:
return
}
}
}
extension GameVC {
private func copyItems(coordinator: UICollectionViewDropCoordinator,
destinationIndexPath: IndexPath, collectionView: UICollectionView) {
collectionView.performBatchUpdates({
var indexPaths = [IndexPath]()
for (index, item) in coordinator.items.enumerated() {
let indexPath = IndexPath(row: destinationIndexPath.row + index,
section: destinationIndexPath.section)
if collectionView == self.collectionView {
guard let dragCoordinator =
coordinator.session.localDragSession?.localContext as?
DragCoordinator
else { return }
answers.remove(at: dragCoordinator.sourceIndexPath.row)
questions.remove(at: indexPath.row)
questions.insert(item.dragItem.localObject as! String,
at: indexPath.row)
if questions×count == 4 {
isCountFour = true
}else{
isCountFour = false
}
}
indexPaths.append(indexPath)
}
collectionView.insertItems(at: indexPaths)
print(answers, questions, originalQuesArray)
self.view.endEditing(true)
let newVC = self.storyboard?.instantiateViewController(withIdentifier:
"SuccessAlertVC") as! SuccessAlertVC
newVC.isPassed = (questions == originalQuesArray)
newVC.delegate = self
newVC.view.backgroundColor = UIColor(white: 0, alpha: 0.5)
self.definesPresentationContext = true
self.providesPresentationContextTransitionStyle = true
newVC.modalPresentationStyle = .overFullScreen
DispatchQueue.main.async {
self.present(newVC, animated: true, completion: nil)
}
})
}
}
// MARK: - Banner Ads Delegate Methods
extension GameVC: GADBannerViewDelegate {
// Banner
func initAdMobBanner() {
adBannerView?.adSize = GADAdSizeFromCGSize(CGSize(width:
view.frame.size.width, height: bannerHeight))
adBannerView?.frame = CGRect(x: 0, y: view.frame.size.height-
bannerHeight-bottomSpacenotBar, width: view.frame.size.width, height:
bannerHeight)
adBannerView?.adUnitID = kGoogleBannerAppUnitID()
adBannerView?.rootViewController = self
adBannerView?.delegate = self
view.addSubview(adBannerView!)
let request = GADRequest()
//request×testDevices = myTestDevices
adBannerView?.load(request)
}
// Hide the banner
func hideBanner(_ banner: UIView) {
UIView.beginAnimations("hideBanner", context: nil)
banner.frame = CGRect(x: view.frame.size.width/2 -
banner.frame.size.width/2, y: view.frame.size.height-bottomSpacenotBar -
banner.frame.size.height, width: banner.frame.size.width, height:
banner.frame.size.height)
UIView.commitAnimations()
banner.isHidden = true
}
// Show the banner
func showBanner(_ banner: UIView) {
UIView.beginAnimations("showBanner", context: nil)
banner.frame = CGRect(x: view.frame.size.width/2 -
banner.frame.size.width/2, y: view.frame.size.height-bottomSpacenotBar -
banner.frame.size.height, width: banner.frame.size.width, height:
banner.frame.size.height)
UIView.commitAnimations()
banner.isHidden = false
}
// AdMob banner available
func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
bottomConstant.constant = bannerHeight
self.view.layoutIfNeeded()
showBanner(adBannerView!)
}
func bannerView(_ bannerView: GADBannerView,
didFailToReceiveAdWithError error: Error) {
print("error :",error.localizedDescription)
hideBanner(adBannerView!)
}
}