I have an Ionic 2 app, and I need to download audios from soundcloud. I already have the url that I need to do the request:
let url = `https://api.soundcloud
My problem was that soundcloud returned a response with redirect. I had to detect the redirect state and manually redirect to the response.headers.Location
That is the working code:
public download(localAudio: LocalAudio): void {
let fileName: string = localAudio.id + '.mp3';
var audio: StorageAudio = {
localAudio: localAudio,
url: `https://api.soundcloud.com/tracks/${localAudio.id}/download?client_id=${this.SC_CLIENT_ID}`,
fileName: fileName,
filePath: this.file.dataDirectory + fileName
};
if (this.platform.is('ios')) {
audio.filePath = audio.filePath.replace(/^file:\/\//, '');
}
this.toastNotifications.showStartingDownloadMsg();
this.http.downloadFile(audio.url, {}, {}, audio.filePath).then(response => {
this.toastNotifications.showDownloadCompleteMsg();
this.storeAudioInformation(audio);
}).catch(response => {
/**
* Handle redirects if exist.
*/
if (this.hasRedirection(response)) {
console.log("Redirect to " + response.headers.Location);
audio.url = response.headers.Location;
this.redirectToDownload(audio);
} else {
this.toastNotifications.showDownloadErrorMsg();
}
});
}
public hasRedirection(response: any): boolean {
return (response.headers.Location && (response.status === 301 || response.status === 302));
}
public redirectToDownload(audio: StorageAudio): void {
this.http.downloadFile(audio.url, {}, {}, audio.filePath).then(response => {
this.toastNotifications.showDownloadCompleteMsg();
this.storeAudioInformation(audio);
}).catch(response => {
console.log("Error catch: " + JSON.stringify(response));
});
}