After selecting a video from the Photo Library I obtained the NSURL of the video with info[UIImagePickerControllerReferenceURL]
.
if let selectedVideo = info[UIImagePickerControllerReferenceURL] as? NSURL, let videoURLString = selectedVideo.absoluteString {
print(videoURLString) // print unwrapped url as string
videoView.configure(url: videoURLString)
videoView.isLoop = true
videoView.play()
} else {
print("Error in unwrapping selected video as a local file URL!")
}
I properly unwrapped it and configured my UIView to play after passing the String. Here is the configure function of videoView.
func configure(url: String) {
if let videoURL = URL(string: url) {
player = AVPlayer(url: videoURL)
playerLayer = AVPlayerLayer(player: player)
playerLayer?.frame = bounds
playerLayer?.videoGravity = AVLayerVideoGravity.resize
if let playerLayer = self.playerLayer {
layer.addSublayer(playerLayer)
}
NotificationCenter.default.addObserver(self, selector: #selector(reachTheEndOfTheVideo(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
}
}
This worked just fine in simulator on an iPhone 8 Plus, but after running on my own iPhone 8 Plus, the UIView that would play the video was not loading, nor was I getting an error message. I later realized that UIImagePickerControllerReferenceURL
was deprecated as of iOS 11.0 even though documentation does state it should be supported iOS 4.1+.
I used UIImagePickerControllerMediaURL
instead and then it finally worked on my phone as well as the simulator.
I did not receive an error either times and print(videoURLString)
was properly printing the asset URL. To find this took quite sometime. How can I better guard the application against bugs like this when troubleshooting? If I cannot use optional binding, how else can I print an error for these kinds of bugs?