-
Notifications
You must be signed in to change notification settings - Fork 0
/
NowPlayingViewController.swift
366 lines (282 loc) · 12.5 KB
/
NowPlayingViewController.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
//
// NowPlayingViewController.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 AVKit
//*****************************************************************
// NowPlayingViewControllerDelegate
//*****************************************************************
protocol NowPlayingViewControllerDelegate: class {
func didPressPlayingButton()
func didPressStopButton()
func didPressNextButton()
func didPressPreviousButton()
}
//*****************************************************************
// NowPlayingViewController
//*****************************************************************
class NowPlayingViewController: UIViewController {
weak var delegate: NowPlayingViewControllerDelegate?
// MARK: - IB UI
@IBOutlet weak var albumHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var albumImageView: SpringImageView!
@IBOutlet weak var artistLabel: UILabel!
@IBOutlet weak var playingButton: UIButton!
@IBOutlet weak var songLabel: SpringLabel!
@IBOutlet weak var stationDescLabel: UILabel!
@IBOutlet weak var volumeParentView: UIView!
@IBOutlet weak var previousButton: UIButton!
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var airPlayView: UIView!
// MARK: - Properties
var currentStation: RadioStation!
var currentTrack: Track!
var newStation = true
var nowPlayingImageView: UIImageView!
let radioPlayer = FRadioPlayer.shared
var mpVolumeSlider: UISlider?
//*****************************************************************
// MARK: - ViewDidLoad
//*****************************************************************
override func viewDidLoad() {
super.viewDidLoad()
// Create Now Playing BarItem
createNowPlayingAnimation()
// Set AlbumArtwork Constraints
optimizeForDeviceSize()
// Set View Title
self.title = currentStation.name
// Set UI
albumImageView.image = currentTrack.artworkImage
stationDescLabel.text = currentStation.desc
stationDescLabel.isHidden = currentTrack.artworkLoaded
// Check for station change
newStation ? stationDidChange() : playerStateDidChange(radioPlayer.state, animate: false)
// Setup volumeSlider
setupVolumeSlider()
// Setup AirPlayButton
setupAirPlayButton()
// Hide / Show Next/Previous buttons
previousButton.isHidden = hideNextPreviousButtons
nextButton.isHidden = hideNextPreviousButtons
}
//*****************************************************************
// MARK: - Setup
//*****************************************************************
func setupVolumeSlider() {
// Note: This slider implementation uses a MPVolumeView
// The volume slider only works in devices, not the simulator.
for subview in MPVolumeView().subviews {
guard let volumeSlider = subview as? UISlider else { continue }
mpVolumeSlider = volumeSlider
}
guard let mpVolumeSlider = mpVolumeSlider else { return }
volumeParentView.addSubview(mpVolumeSlider)
mpVolumeSlider.translatesAutoresizingMaskIntoConstraints = false
mpVolumeSlider.leftAnchor.constraint(equalTo: volumeParentView.leftAnchor).isActive = true
mpVolumeSlider.rightAnchor.constraint(equalTo: volumeParentView.rightAnchor).isActive = true
mpVolumeSlider.centerYAnchor.constraint(equalTo: volumeParentView.centerYAnchor).isActive = true
mpVolumeSlider.setThumbImage(#imageLiteral(resourceName: "slider-ball"), for: .normal)
}
func setupAirPlayButton() {
guard !hideAirPlayButton else {
airPlayView.isHidden = true
return
}
if #available(iOS 11.0, *) {
let airPlayButton = AVRoutePickerView(frame: airPlayView.bounds)
airPlayButton.activeTintColor = globalTintColor
airPlayButton.tintColor = .gray
airPlayView.backgroundColor = .clear
airPlayView.addSubview(airPlayButton)
} else {
let airPlayButton = MPVolumeView(frame: airPlayView.bounds)
airPlayButton.showsVolumeSlider = false
airPlayView.backgroundColor = .clear
airPlayView.addSubview(airPlayButton)
}
}
func stationDidChange() {
radioPlayer.radioURL = URL(string: currentStation.streamURL)
albumImageView.image = currentTrack.artworkImage
stationDescLabel.text = currentStation.desc
stationDescLabel.isHidden = currentTrack.artworkLoaded
title = currentStation.name
}
//*****************************************************************
// MARK: - Player Controls (Play/Pause/Volume)
//*****************************************************************
// Actions
@IBAction func playingPressed(_ sender: Any) {
delegate?.didPressPlayingButton()
}
@IBAction func stopPressed(_ sender: Any) {
delegate?.didPressStopButton()
}
@IBAction func nextPressed(_ sender: Any) {
delegate?.didPressNextButton()
}
@IBAction func previousPressed(_ sender: Any) {
delegate?.didPressPreviousButton()
}
//*****************************************************************
// MARK: - Load station/track
//*****************************************************************
func load(station: RadioStation?, track: Track?, isNewStation: Bool = true) {
guard let station = station else { return }
currentStation = station
currentTrack = track
newStation = isNewStation
}
func updateTrackMetadata(with track: Track?) {
guard let track = track else { return }
currentTrack.artist = track.artist
currentTrack.title = track.title
updateLabels()
}
// Update track with new artwork
func updateTrackArtwork(with track: Track?) {
guard let track = track else { return }
// Update track struct
currentTrack.artworkImage = track.artworkImage
currentTrack.artworkLoaded = track.artworkLoaded
albumImageView.image = currentTrack.artworkImage
if track.artworkLoaded {
// Animate artwork
albumImageView.animation = "wobble"
albumImageView.duration = 2
albumImageView.animate()
stationDescLabel.isHidden = true
} else {
stationDescLabel.isHidden = false
}
// Force app to update display
view.setNeedsDisplay()
}
private func isPlayingDidChange(_ isPlaying: Bool) {
playingButton.isSelected = isPlaying
startNowPlayingAnimation(isPlaying)
}
func playbackStateDidChange(_ playbackState: FRadioPlaybackState, animate: Bool) {
let message: String?
switch playbackState {
case .paused:
message = "Station Paused..."
case .playing:
message = nil
case .stopped:
message = "Station Stopped..."
}
updateLabels(with: message, animate: animate)
isPlayingDidChange(radioPlayer.isPlaying)
}
func playerStateDidChange(_ state: FRadioPlayerState, animate: Bool) {
let message: String?
switch state {
case .loading:
message = "Loading Station ..."
case .urlNotSet:
message = "Station URL not valide"
case .readyToPlay, .loadingFinished:
playbackStateDidChange(radioPlayer.playbackState, animate: animate)
return
case .error:
message = "Error Playing"
}
updateLabels(with: message, animate: animate)
}
//*****************************************************************
// MARK: - UI Helper Methods
//*****************************************************************
func optimizeForDeviceSize() {
// Adjust album size to fit iPhone 4s, 6s & 6s+
let deviceHeight = self.view.bounds.height
if deviceHeight == 480 {
albumHeightConstraint.constant = 106
view.updateConstraints()
} else if deviceHeight == 667 {
albumHeightConstraint.constant = 230
view.updateConstraints()
} else if deviceHeight > 667 {
albumHeightConstraint.constant = 260
view.updateConstraints()
}
}
func updateLabels(with statusMessage: String? = nil, animate: Bool = true) {
guard let statusMessage = statusMessage else {
// Radio is (hopefully) streaming properly
songLabel.text = currentTrack.title
artistLabel.text = currentTrack.artist
shouldAnimateSongLabel(animate)
return
}
// There's a an interruption or pause in the audio queue
// Update UI only when it's not aleary updated
guard songLabel.text != statusMessage else { return }
songLabel.text = statusMessage
artistLabel.text = currentStation.name
if animate {
songLabel.animation = "flash"
songLabel.repeatCount = 3
songLabel.animate()
}
}
// Animations
func shouldAnimateSongLabel(_ animate: Bool) {
// Animate if the Track has album metadata
guard animate, currentTrack.title != currentStation.name else { return }
// songLabel animation
songLabel.animation = "zoomIn"
songLabel.duration = 1.5
songLabel.damping = 1
songLabel.animate()
}
func createNowPlayingAnimation() {
// Setup ImageView
nowPlayingImageView = UIImageView(image: UIImage(named: "NowPlayingBars-3"))
nowPlayingImageView.autoresizingMask = []
nowPlayingImageView.contentMode = UIView.ContentMode.center
// Create Animation
nowPlayingImageView.animationImages = AnimationFrames.createFrames()
nowPlayingImageView.animationDuration = 0.7
// Create Top BarButton
let barButton = UIButton(type: .custom)
barButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
barButton.addSubview(nowPlayingImageView)
nowPlayingImageView.center = barButton.center
let barItem = UIBarButtonItem(customView: barButton)
self.navigationItem.rightBarButtonItem = barItem
}
func startNowPlayingAnimation(_ animate: Bool) {
animate ? nowPlayingImageView.startAnimating() : nowPlayingImageView.stopAnimating()
}
//*****************************************************************
// MARK: - Segue
//*****************************************************************
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == "InfoDetail", let infoController = segue.destination as? InfoDetailViewController else { return }
infoController.currentStation = currentStation
}
@IBAction func infoButtonPressed(_ sender: UIButton) {
performSegue(withIdentifier: "InfoDetail", sender: self)
}
@IBAction func shareButtonPressed(_ sender: UIButton) {
let radioShoutout = "I'm listening to \(currentStation.name) via Daniel Radio Project"
let shareImage = ShareImageGenerator(radioShoutout: radioShoutout, track: currentTrack).generate()
let activityViewController = UIActivityViewController(activityItems: [radioShoutout, shareImage], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceRect = CGRect(x: view.center.x, y: view.center.y, width: 0, height: 0)
activityViewController.popoverPresentationController?.sourceView = view
activityViewController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
activityViewController.completionWithItemsHandler = {(activityType: UIActivity.ActivityType?, completed:Bool, returnedItems:[Any]?, error: Error?) in
if completed {
// do something on completion if you want
}
}
present(activityViewController, animated: true, completion: nil)
}
}