/
StationsViewController.swift
517 lines (398 loc) · 18.4 KB
/
StationsViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//
// StationsViewController.swift
// Beloe Radio
//
// Created by Danila Chub on 5/1/21.
// Copyright (c) 2020 Beloe-Radio.by. All rights reserved.
//
import UIKit
import MediaPlayer
import AVFoundation
import GoogleMobileAds
class StationsViewController: UIViewController {
@IBOutlet weak var banner: GADBannerView!
// MARK: - IB UI
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var stationNowPlayingButton: UIButton!
@IBOutlet weak var nowPlayingAnimationImageView: UIImageView!
// MARK: - Properties
let radioPlayer = RadioPlayer()
// Weak reference to update the NowPlayingViewController
weak var nowPlayingViewController: NowPlayingViewController?
// MARK: - Lists
var stations = [RadioStation]() {
didSet {
guard stations != oldValue else { return }
stationsDidUpdate()
}
}
var searchedStations = [RadioStation]()
var previousStation: RadioStation?
// MARK: - UI
var searchController: UISearchController = {
return UISearchController(searchResultsController: nil)
}()
var refreshControl: UIRefreshControl = {
return UIRefreshControl()
}()
//*****************************************************************
// MARK: - ViewDidLoad
//*****************************************************************
override func viewDidLoad() {
super.viewDidLoad()
banner.adUnitID = "ca-app-pub-2636701935410355/7642365303"
banner.load(GADRequest())
banner.rootViewController = self
// Register 'Nothing Found' cell xib
let cellNib = UINib(nibName: "NothingFoundCell", bundle: nil)
tableView.register(cellNib, forCellReuseIdentifier: "NothingFound")
// Setup Player
radioPlayer.delegate = self
// Load Data
loadStationsFromJSON()
// Setup TableView
tableView.backgroundColor = .clear
tableView.backgroundView = nil
tableView.separatorStyle = .none
// Setup Pull to Refresh
setupPullToRefresh()
// Create NowPlaying Animation
createNowPlayingAnimation()
// Activate audioSession
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch {
if kDebugLog { print("audioSession could not be activated") }
}
// Setup Search Bar
setupSearchController()
// Setup Remote Command Center
setupRemoteCommandCenter()
// Setup Handoff User Activity
setupHandoffUserActivity()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
title = "Beloe Radio"
}
//*****************************************************************
// MARK: - Setup UI Elements
//*****************************************************************
func setupPullToRefresh() {
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh", attributes: [.foregroundColor: UIColor.white])
refreshControl.backgroundColor = .black
refreshControl.tintColor = .white
refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
tableView.addSubview(refreshControl)
}
func createNowPlayingAnimation() {
nowPlayingAnimationImageView.animationImages = AnimationFrames.createFrames()
nowPlayingAnimationImageView.animationDuration = 0.7
}
func createNowPlayingBarButton() {
guard navigationItem.rightBarButtonItem == nil else { return }
let btn = UIBarButtonItem(title: "", style: .plain, target: self, action:#selector(nowPlayingBarButtonPressed))
btn.image = UIImage(named: "btn-nowPlaying")
navigationItem.rightBarButtonItem = btn
}
//*****************************************************************
// MARK: - Actions
//*****************************************************************
@objc func nowPlayingBarButtonPressed() {
performSegue(withIdentifier: "NowPlaying", sender: self)
}
@IBAction func nowPlayingPressed(_ sender: UIButton) {
performSegue(withIdentifier: "NowPlaying", sender: self)
}
@objc func refresh(sender: AnyObject) {
// Pull to Refresh
loadStationsFromJSON()
// Wait 2 seconds then refresh screen
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.refreshControl.endRefreshing()
self.view.setNeedsDisplay()
}
}
//*****************************************************************
// MARK: - Load Station Data
//*****************************************************************
func loadStationsFromJSON() {
// Turn on network indicator in status bar
UIApplication.shared.isNetworkActivityIndicatorVisible = true
// Get the Radio Stations
DataManager.getStationDataWithSuccess() { (data) in
// Turn off network indicator in status bar
defer {
DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = false }
}
if kDebugLog { print("Stations JSON Found") }
guard let data = data, let jsonDictionary = try? JSONDecoder().decode([String: [RadioStation]].self, from: data), let stationsArray = jsonDictionary["station"] else {
if kDebugLog { print("JSON Station Loading Error") }
return
}
self.stations = stationsArray
}
}
//*****************************************************************
// MARK: - Segue
//*****************************************************************
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == "NowPlaying", let nowPlayingVC = segue.destination as? NowPlayingViewController else { return }
title = ""
let newStation: Bool
if let indexPath = (sender as? IndexPath) {
// User clicked on row, load/reset station
radioPlayer.station = searchController.isActive ? searchedStations[indexPath.row] : stations[indexPath.row]
newStation = radioPlayer.station != previousStation
previousStation = radioPlayer.station
} else {
// User clicked on Now Playing button
newStation = false
}
nowPlayingViewController = nowPlayingVC
nowPlayingVC.load(station: radioPlayer.station, track: radioPlayer.track, isNewStation: newStation)
nowPlayingVC.delegate = self
}
//*****************************************************************
// MARK: - Private helpers
//*****************************************************************
private func stationsDidUpdate() {
DispatchQueue.main.async {
self.tableView.reloadData()
guard let currentStation = self.radioPlayer.station else { return }
// Reset everything if the new stations list doesn't have the current station
if self.stations.firstIndex(of: currentStation) == nil { self.resetCurrentStation() }
}
}
// Reset all properties to default
private func resetCurrentStation() {
radioPlayer.resetRadioPlayer()
nowPlayingAnimationImageView.stopAnimating()
stationNowPlayingButton.setTitle("Choose a station above to begin", for: .normal)
stationNowPlayingButton.isEnabled = false
navigationItem.rightBarButtonItem = nil
}
// Update the now playing button title
private func updateNowPlayingButton(station: RadioStation?, track: Track?) {
guard let station = station else { resetCurrentStation(); return }
var playingTitle = station.name + ": "
if track?.title == station.name {
playingTitle += "Now playing ..."
} else if let track = track {
playingTitle += track.title + " - " + track.artist
}
stationNowPlayingButton.setTitle(playingTitle, for: .normal)
stationNowPlayingButton.isEnabled = true
createNowPlayingBarButton()
}
func startNowPlayingAnimation(_ animate: Bool) {
animate ? nowPlayingAnimationImageView.startAnimating() : nowPlayingAnimationImageView.stopAnimating()
}
private func getIndex(of station: RadioStation?) -> Int? {
guard let station = station, let index = stations.firstIndex(of: station) else { return nil }
return index
}
//*****************************************************************
// MARK: - Remote Command Center Controls
//*****************************************************************
func setupRemoteCommandCenter() {
// Get the shared MPRemoteCommandCenter
let commandCenter = MPRemoteCommandCenter.shared()
// Add handler for Play Command
commandCenter.playCommand.addTarget { event in
return .success
}
// Add handler for Pause Command
commandCenter.pauseCommand.addTarget { event in
return .success
}
// Add handler for Next Command
commandCenter.nextTrackCommand.addTarget { event in
return .success
}
// Add handler for Previous Command
commandCenter.previousTrackCommand.addTarget { event in
return .success
}
}
//*****************************************************************
// MARK: - MPNowPlayingInfoCenter (Lock screen)
//*****************************************************************
func updateLockScreen(with track: Track?) {
// Define Now Playing Info
var nowPlayingInfo = [String : Any]()
if let image = track?.artworkImage {
nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size, requestHandler: { size -> UIImage in
return image
})
}
if let artist = track?.artist {
nowPlayingInfo[MPMediaItemPropertyArtist] = artist
}
if let title = track?.title {
nowPlayingInfo[MPMediaItemPropertyTitle] = title
}
// Set the metadata
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
}
//*****************************************************************
// MARK: - TableViewDataSource
//*****************************************************************
extension StationsViewController: UITableViewDataSource {
@objc(tableView:heightForRowAtIndexPath:)
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 90.0
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.isActive {
return searchedStations.count
} else {
return stations.isEmpty ? 1 : stations.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if stations.isEmpty {
let cell = tableView.dequeueReusableCell(withIdentifier: "NothingFound", for: indexPath)
cell.backgroundColor = .clear
cell.selectionStyle = .none
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "StationCell", for: indexPath) as! StationTableViewCell
// alternate background color
cell.backgroundColor = (indexPath.row % 2 == 0) ? UIColor.clear : UIColor.black.withAlphaComponent(0.2)
let station = searchController.isActive ? searchedStations[indexPath.row] : stations[indexPath.row]
cell.configureStationCell(station: station)
return cell
}
}
}
//*****************************************************************
// MARK: - TableViewDelegate
//*****************************************************************
extension StationsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
performSegue(withIdentifier: "NowPlaying", sender: indexPath)
}
}
//*****************************************************************
// MARK: - UISearchControllerDelegate / Setup
//*****************************************************************
extension StationsViewController: UISearchResultsUpdating {
func setupSearchController() {
guard searchable else { return }
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.sizeToFit()
// Add UISearchController to the tableView
tableView.tableHeaderView = searchController.searchBar
tableView.tableHeaderView?.backgroundColor = UIColor.clear
definesPresentationContext = true
searchController.hidesNavigationBarDuringPresentation = false
// Style the UISearchController
searchController.searchBar.barTintColor = UIColor.clear
searchController.searchBar.tintColor = UIColor.white
// Hide the UISearchController
tableView.setContentOffset(CGPoint(x: 0.0, y: searchController.searchBar.frame.size.height), animated: false)
// iOS 13 or greater
if #available(iOS 13.0, *) {
// Make text readable in black searchbar
searchController.searchBar.barStyle = .black
// Set a black keyborad for UISearchController's TextField
searchController.searchBar.searchTextField.keyboardAppearance = .dark
} else {
let searchTextField = searchController.searchBar.value(forKey: "_searchField") as? UITextField
searchTextField?.keyboardAppearance = .dark
}
}
func updateSearchResults(for searchController: UISearchController) {
guard let searchText = searchController.searchBar.text else { return }
searchedStations.removeAll(keepingCapacity: false)
searchedStations = stations.filter { $0.name.range(of: searchText, options: [.caseInsensitive]) != nil }
self.tableView.reloadData()
}
}
//*****************************************************************
// MARK: - RadioPlayerDelegate
//*****************************************************************
extension StationsViewController: RadioPlayerDelegate {
func playerStateDidChange(_ playerState: FRadioPlayerState) {
nowPlayingViewController?.playerStateDidChange(playerState, animate: true)
}
func playbackStateDidChange(_ playbackState: FRadioPlaybackState) {
nowPlayingViewController?.playbackStateDidChange(playbackState, animate: true)
startNowPlayingAnimation(radioPlayer.player.isPlaying)
}
func trackDidUpdate(_ track: Track?) {
updateLockScreen(with: track)
updateNowPlayingButton(station: radioPlayer.station, track: track)
updateHandoffUserActivity(userActivity, station: radioPlayer.station, track: track)
nowPlayingViewController?.updateTrackMetadata(with: track)
}
func trackArtworkDidUpdate(_ track: Track?) {
updateLockScreen(with: track)
nowPlayingViewController?.updateTrackArtwork(with: track)
}
}
//*****************************************************************
// MARK: - Handoff Functionality - GH
//*****************************************************************
extension StationsViewController {
func setupHandoffUserActivity() {
userActivity = NSUserActivity(activityType: NSUserActivityTypeBrowsingWeb)
userActivity?.becomeCurrent()
}
func updateHandoffUserActivity(_ activity: NSUserActivity?, station: RadioStation?, track: Track?) {
guard let activity = activity else { return }
activity.webpageURL = (track?.title == station?.name) ? nil : getHandoffURL(from: track)
updateUserActivityState(activity)
}
override func updateUserActivityState(_ activity: NSUserActivity) {
super.updateUserActivityState(activity)
}
private func getHandoffURL(from track: Track?) -> URL? {
guard let track = track else { return nil }
var components = URLComponents()
components.scheme = "https"
components.host = "google.com"
components.path = "/search"
components.queryItems = [URLQueryItem]()
components.queryItems?.append(URLQueryItem(name: "q", value: "\(track.artist) \(track.title)"))
return components.url
}
}
//*****************************************************************
// MARK: - NowPlayingViewControllerDelegate
//*****************************************************************
extension StationsViewController: NowPlayingViewControllerDelegate {
func didPressPlayingButton() {
radioPlayer.player.togglePlaying()
}
func didPressStopButton() {
radioPlayer.player.stop()
}
func didPressNextButton() {
guard let index = getIndex(of: radioPlayer.station) else { return }
radioPlayer.station = (index + 1 == stations.count) ? stations[0] : stations[index + 1]
handleRemoteStationChange()
}
func didPressPreviousButton() {
guard let index = getIndex(of: radioPlayer.station) else { return }
radioPlayer.station = (index == 0) ? stations.last : stations[index - 1]
handleRemoteStationChange()
}
func handleRemoteStationChange() {
if let nowPlayingVC = nowPlayingViewController {
// If nowPlayingVC is presented
nowPlayingVC.load(station: radioPlayer.station, track: radioPlayer.track)
nowPlayingVC.stationDidChange()
} else if let station = radioPlayer.station {
// If nowPlayingVC is not presented (change from remote controls)
radioPlayer.player.radioURL = URL(string: station.streamURL)
}
}
}