Files
Woka_Native_iOS/WOKA/WOKAFM/ViewModel/WokaFMVM.swift
BilalKhanWDI 7efcbb2d24 - Worked on my list and notification bottom Banner
- Tc - 69 fixed
- Tc - 70 fixed
- TC 71 fixed
- Added local ads to fm and more section
- Added local ads to mylist
- Fixed a bug for sync
* Fixed the crashing by temporary updating the wokastaging with raw data
2024-10-01 19:57:04 +05:30

232 lines
8.6 KiB
Swift

//
// WokaFMVM.swift
// WOKA
//
// Created by MacBook Pro on 01/08/24.
//
import UIKit
import AVFoundation
import GoogleMobileAds
import MediaPlayer
class WokaFMVM{
weak var vc : WokaFMVC!
var player: AVPlayer!
var playerItem: AVPlayerItem!
var startTimeStamp = Date()
var bottomBannerView = GADBannerView()
// if retry count is 4 reset it to 0
var retryCount = 0
func initView(){
startTimeStamp = Date()
vc.mainView.roundCorners(radius: 10, corners: [.topLeft, .topRight])
let color1 = #colorLiteral(red: 0.5921568627, green: 0.2588235294, blue: 0.8941176471, alpha: 1)
let color2 = #colorLiteral(red: 0.368627451, green: 0.1215686275, blue: 0.768627451, alpha: 1)
vc.roundView.applyGradient(colors: [color2, color1], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
vc.playBtn.applyGradientBtn(colors: [color2, color1], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 0))
vc.playBtn.roundCorner()
vc.mainView.roundCorners(radius: 10, corners: [.topLeft, . topRight])
setupPlayer()
vc.addObservers()
setupAudioSession()
vc.blackView.addTapGesture { [weak self] in
guard let self else{return}
PersistentStorage.shared.addRadioCount()
if let postID = AuthFunc.shareInstance.staticURLs?.liveFmData?.id {
let duration = DateFormatterLib.dateDifferenceINT(date1: self.startTimeStamp, date2: Date())
AuthFunc.shareInstance.userVideoView(postID: postID, postType: PostType.FM.rawValue, duration: duration, catID: 0) { _ in}
}
self.vc.dismiss(animated: true)
}
setGoogleAd()
// updateNowPlayingInfo()
}
// MARK: - SetupAd
func stopMPNowPlayin(){
MPNowPlayingInfoCenter.default().nowPlayingInfo = [:]
UIApplication.shared.endReceivingRemoteControlEvents()
let commandCenter = MPRemoteCommandCenter.shared()
// Disable play/pause commands
commandCenter.playCommand.removeTarget(nil)
commandCenter.pauseCommand.removeTarget(nil)
}
func setupNowPlayingInfo() {
let nowPlayingInfoCenter = MPNowPlayingInfoCenter.default()
var nowPlayingInfo: [String: Any] = [:]
// Set the media title, artist, and album name
nowPlayingInfo[MPMediaItemPropertyTitle] = "Live FM"
nowPlayingInfo[MPMediaItemPropertyArtist] = "WOKA"
nowPlayingInfo[MPMediaItemPropertyAlbumTitle] = ""
nowPlayingInfo[MPNowPlayingInfoPropertyIsLiveStream] = true
if let originalImage = UIImage(named: "MasilaCharacter") {
let artworkImage = imageWithBackground(color: #colorLiteral(red: 0.4495816827, green: 0.2344398499, blue: 0.8120074868, alpha: 1), originalImage: originalImage)
let artwork = MPMediaItemArtwork(boundsSize: originalImage.size) { size in
return artworkImage ?? originalImage
}
nowPlayingInfo[MPMediaItemPropertyArtwork] = artwork
}
// Set the duration and current playback position
if let currentItem = player.currentItem {
nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = currentItem.asset.duration.seconds
nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = player.currentTime().seconds
nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate
}
// Assign the nowPlayingInfo to the center
nowPlayingInfoCenter.nowPlayingInfo = nowPlayingInfo
}
func setupRemoteCommandCenter() {
let commandCenter = MPRemoteCommandCenter.shared()
// Enable play command
commandCenter.playCommand.addTarget { [weak self] event in
guard let self else{return .commandFailed}
if player.rate == 0.0 {
player.play()
return .success
}
return .commandFailed
}
// Enable pause command
commandCenter.pauseCommand.addTarget { [weak self] event in
guard let self else{return .commandFailed}
if player.rate == 1.0 {
player.pause()
return .success
}
return .commandFailed
}
// Enable next and previous track commands if needed
commandCenter.nextTrackCommand.isEnabled = false
commandCenter.previousTrackCommand.isEnabled = false
}
func imageWithBackground(color: UIColor, originalImage: UIImage) -> UIImage? {
let size = originalImage.size
UIGraphicsBeginImageContextWithOptions(size, false, originalImage.scale)
let rect = CGRect(origin: CGPoint.zero, size: size)
// Fill the background with a color
color.setFill()
UIRectFill(rect)
// Draw the original image on top
originalImage.draw(in: rect)
// Capture the new image with background
let imageWithBackground = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithBackground
}
func updateNowPlayingInfo() {
if let currentItem = player.currentItem {
var nowPlayingInfo = MPNowPlayingInfoCenter.default().nowPlayingInfo ?? [:]
nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = player.currentTime().seconds
nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
}
func setGoogleAd(){
/*
First check if webSeries ad is present via slug, then check for Local Ads, if not then check google ads.
*/
if let adsData = AuthFunc.shareInstance.adsData, let fmAd = adsData.result?.filter({$0.slug == AdsEnum.fm.rawValue}).first{
// check if ads data contains LocalAD for webseries
if let advertisement = fmAd.advertisement,let bannerImage = advertisement.bannerImage{
vc.imageAdView.imageURL(bannerImage, color: .white)
vc.imageAdView.alpha = 0
let height = UIScreen.main.bounds.width * 0.192
vc.imageAdHeight.constant = height
UIView.animate(withDuration: 0.2, animations: { [weak self] in
guard let self else{return}
vc.imageAdView.alpha = 1
vc.imageAdView.isHidden = false
})
vc.imageAdView.addTapGesture {
if let adID = fmAd.id{
PersistentStorage.shared.addAdsCount(adID: adID ,clicks: 1)
}
if let adLink = fmAd.advertisement?.adLink ,let url = URL(string: adLink), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url)
}
}
}else{
/*
Show google ads with dispatch queue.
*/
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: { [weak self] in
guard let self else{return}
AdReusable.sharedInstance.setupBannerAd(bannerView: self.bottomBannerView, in: vc.imageAdView, adUnitID: K.GoogleAdIDs.wokaFM, viewController: self.vc)
})
}
}
}
// MARK: - Setup AV & Player
func setupAudioSession() {
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(.playback, mode: .default)
try session.setActive(true)
} catch {
print("Failed to set up audio session")
}
}
func setupPlayer() {
guard let data = AuthFunc.shareInstance.staticURLs , let liveFmURL = data.liveFmData?.liveFmURL else{
AuthFunc.shareInstance.getStaticURLs()
self.vc.toast(msg: "Issue with radio, please try after sometime.", time: 2)
return
}
guard let url = URL(string: liveFmURL) else{return}
// guard let url = URL(string: "https://a9.asurahosting.com:7530/radio.mp3") else{return}
playerItem = AVPlayerItem(url: url)
player = AVPlayer(playerItem: playerItem)
player.play()
// setGoogleAd()
}
func retryConnect(){
vc.activityIndicator.startAnimating()
vc.playBtn.isEnabled = false
setupPlayer()
vc.addObservers()
setupAudioSession()
}
}