[ad_1]
In a private venture of mine, I’ve created an API caller to retrieve a person’s saved tracks from the Spotify API. The Spotify endpoint which I’m utilizing has a restrict (most of fifty tracks per request) in addition to an offset (beginning index of first observe in request), which is why I made a decision to make use of a FOR loop to get a collection of observe pages (every 50 tracks) and append them to a worldwide array. The information is loaded from the primary thread, and whereas the information is being requested, I show a toddler view controller with a spinner view. As soon as the information request has accomplished, I take away the spinner view, and transition to a different view controller (passing the information as a property).
I’ve tried many issues, however the array of tracks is all the time empty following the API request. I’ve a sense it has to do with the synchronicity of my request, or possibly its potential that I am not dealing with it appropriately. Ideally, I wish to wait till the request from my API finishes, then append the consequence to the array. Do you could have any options on how I might clear up this? Any assist is way appreciated!
func createSpinnerView() {
let loadViewController = LoadViewController.instantiateFromAppStoryboard(appStoryboard: .OrganizeScreen)
add(asChildViewController: loadViewController)
DispatchQueue.important.async { [weak self] in
if (self?.dropdownButton.dropdownLabel.textual content == "My saved music") {
self?.fetchSavedMusic() { tracksArray in
self?.tracksArray = tracksArray
}
}
...
self?.take away(asChildViewController: loadViewController)
self?.navigateToFilterScreen(tracksArray: self!.tracksArray)
}
}
non-public func fetchSavedMusic(completion: @escaping ([Tracks]) -> ()) {
let restrict = 50
var offset = 0
var complete = 200
for _ in stride(from: 0, to: complete, by: restrict) {
getSavedTracks(restrict: restrict, offset: offset) { tracks in
//complete = tracks.complete
self.tracksArray.append(tracks)
}
print(offset, restrict)
offset = offset + 50
}
completion(tracksArray)
}
non-public func getSavedTracks(restrict: Int, offset: Int, completion: @escaping (Tracks) -> ()) {
APICaller.shared.getUsersSavedTracks(restrict: restrict, offset: offset) { (consequence) in
change consequence {
case .success(let mannequin):
completion(mannequin)
print("success")
case .failure(let error):
print("Error retrieving saved tracks: (error.localizedDescription)")
print(error)
}
}
}
non-public func navigateToFilterScreen(tracksArray: [Tracks]) {
let vc = FilterViewController.instantiateFromAppStoryboard(appStoryboard: .OrganizeScreen)
vc.paginatedTracks = tracksArray
present(vc, sender: self)
}
[ad_2]
