0

I am creating a personal playlist in my app using songs that I am pulling from the Spotify SDK. Spotify songs have a uri which makes it so you can only play the tracks with the Spotify player which takes a single string uri and plays it, but I have an entire array of track URI's. To solve this I created a for..in loop to play each individual song, but what happens is it iterates through the entire array and only plays the last track uri in the array.

My question is: Is there a way to have the for..in loop wait for each item to finish playing before going through the rest of the array?

array of track uri's

function that plays each individual URI

2
  • 1
    You should add the code to your post (using the code formatting) instead of linking an image. This will allow others to easily read it or copy/paste to test a solution. Commented Aug 3, 2017 at 15:35
  • 1
    Welcome to StackExchange. I just fixed the image tags in your question. However, please to not post your code as images. Instead, provide them as text. Commented Aug 3, 2017 at 15:35

2 Answers 2

1

If you want to play the songs sequentially (like a playlist), you need to add them a serial DispatchQueue. The serial queue will ensure that only one item is executed inside it at a time and hence only one of the asynchronous requests will execute at a time, meaning that each iteration of the for loop will wait for the previous one to finish.

let queue = DispatchQueue(label: "serial")
for song in playAllSongs{
    queue.async{
        //put all code here that you had inside the for loop
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You shouldn't use a for...in loop to play all songs. Even if you use a synchronous block I'm not sure it will works. A solution is to listen a Notification or to have a completion block called when a song is ended. Then you just have to play the next one in the array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.