CoI tested with somme dummy code.
Problem comes from the fact that player is defined as a State var:
This show : player is nil
struct SatelliteVideoView: View {
@State private var player: AVPlayer?
init() {
if let url = URL(string: "https://swiftanytime-content.s3.ap-south-1.amazonaws.com/SwiftUI-Beginner/Video-Player/iMacAdvertisement.mp4") {
print(url)
player = AVPlayer(url: url)
} else {
print("url is nil")
}
}
var body: some View {
if player != nil {
Text("player is not nil") // VideoPlayer(player: player!)
} else {
Text("player is nil")
}
}
}
But here, player is not nil:
struct SatelliteVideoView: View {
/*@State*/ private var player: AVPlayer?
init() {
if let url = URL(string: "https://swiftanytime-content.s3.ap-south-1.amazonaws.com/SwiftUI-Beginner/Video-Player/iMacAdvertisement.mp4") {
print(url)
player = AVPlayer(url: url)
} else {
print("url is nil")
}
}
var body: some View {
if player != nil {
Text("player is not nil") // VideoPlayer(player: player!)
} else {
Text("player is nil")
}
}
}
Or, if you define player as AVPlayer and not optional, it works:
struct SatelliteVideoView: View {
@State private var player: AVPlayer
init() {
if let url = URL(string: "https://swiftanytime-content.s3.ap-south-1.amazonaws.com/SwiftUI-Beginner/Video-Player/iMacAdvertisement.mp4") {
player = AVPlayer(url: url)
} else {
player = AVPlayer()
}
}
var body: some View {
Text("player is not nil") // VideoPlayer(player: player!)
}
}
Reason is detailed here: https://stackoverflow.com/questions/56691630/swiftui-state-var-initialization-issue
- you cannot change the value of a state var in its struct
- but you can initialise it.
So if you declare as optional AVPlayer, it is initialised as nil. No possible to change later in init().
But if you simply declare as AVPlayer, it is not yet initialised, hence you can set it in init()