-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathFeedsViewModel.swift
More file actions
104 lines (85 loc) · 2.52 KB
/
FeedsViewModel.swift
File metadata and controls
104 lines (85 loc) · 2.52 KB
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
//
// FeedsViewModel.swift
// VideoNavigation-Example
//
// Created by shayanbo on 2023/7/21.
//
import Foundation
import AVKit
import VideoPlayerContainer
import SwiftUI
class FeedsViewModel : ObservableObject {
//MARK: Navigation
@Published var navigator = NavigationPath()
var navigatorBinding: Binding<NavigationPath> {
Binding {
self.navigator
} set: {
self.navigator = $0
}
}
func push(_ video: Video) {
navigator.append(video)
}
//MARK: Search
@Published var searchText = ""
var searchTextBinding: Binding<String> {
Binding {
self.searchText
} set: {
self.searchText = $0
}
}
//MARK: Video Data
@Published var videos = [Video]()
init() {
guard let feedsUrl = Bundle.main.url(forResource: "feeds", withExtension: "json") else {
return
}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
guard let data = try? Data(contentsOf: feedsUrl) else {
return
}
do {
self.videos = try decoder.decode([Video].self, from: data)
} catch {
print(error)
}
}
//MARK: Context
private var contexts = [Video: Context]()
func context(video: Video) -> Context {
if let context = contexts[video] {
return context
} else {
let context = Context()
contexts[video] = context
return context
}
}
//MARK: Active Video
var activeVideo: Video? {
willSet {
guard activeVideo != newValue else { return }
if let activeVideo = activeVideo {
let ctx = context(video: activeVideo)
let player = ctx[RenderService.self].player
if player.rate > 0 {
player.pause()
}
}
if let newValue = newValue {
let ctx = context(video: newValue)
let player = ctx[RenderService.self].player
if player.currentItem == nil {
let item = AVPlayerItem(url: Bundle.main.url(forResource: "demo", withExtension: "mp4")!)
player.replaceCurrentItem(with: item)
player.play()
} else {
player.play()
}
}
}
}
}