Reputation: 15
I'm looking to utilize a "next" button for my app that's playing Youtube videos. My hopes are for the button to increase the index by 1 each time it is clicked. But I can only find info on .startIndex
and I can't figure out how to continue adding one. The code is here:
@IBAction func nextButton(_ sender: NSButton) {
}
@IBOutlet weak var myWebView: WebView!
override func viewDidLoad() {
super.viewDidLoad()
let videoCode = ["ufynqs_COF4", "MXqjDRQbibw", "T3JgUT-fa3A"]
// attempt to add to index
let i = videoCode.index(videoCode.startIndex, offsetBy: 1)
print(i)
let url = URL(string: "https://youtube.com/embed/\(videoCode[i])")
var request = URLRequest(url: url!)
request.setValue("https://youtube.com", forHTTPHeaderField: "Referer")
self.myWebView.mainFrame.load(request)
}
Upvotes: 0
Views: 38
Reputation: 285290
You have to move the token array to the top level of the class and create a counter
let videoCode = ["ufynqs_COF4", "MXqjDRQbibw", "T3JgUT-fa3A"]
var counter = 0
As the code to load the next video is used twice create a method. It increments (and wraps around to zero) the counter.
func loadNextVideo()
{
let url = URL(string: "https://youtube.com/embed")!.appendingPathComponent(videoCode[counter])
var request = URLRequest(url: url)
request.setValue("https://youtube.com", forHTTPHeaderField: "Referer")
self.myWebView.mainFrame.load(request)
counter = (counter + 1) % videoCode.count
}
In viewDidLoad
and in the IBAction
just call the method
override func viewDidLoad() {
super.viewDidLoad()
loadNextVideo()
}
@IBAction func nextButton(_ sender: NSButton) {
loadNextVideo()
}
Upvotes: 1