0

I want to download audio file, save it in photos library and play after download. But this code not saving video in library.

Is it possible to download directly in photos library or any other folder externally.

My code is from here Swift - Download a video from distant URL and save it in an photo album

DispatchQueue.global(qos: .background).async {
        if let url = URL(string: self.audioURL!),
            let urlData = NSData(contentsOf: url) {
            let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0];
            let filePath="\(documentsPath)/tempFile.mp3"
            print(filePath)
            DispatchQueue.main.async {
                urlData.write(toFile: filePath, atomically: true)
                PHPhotoLibrary.shared().performChanges({
                    PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: filePath))
                }) { completed, error in
                    if completed {
                        print("Video is saved!")
                    }
                }
            }
        }
    }
Naresh
  • 16,698
  • 6
  • 112
  • 113

1 Answers1

3

You can't save audio in the photos library, You can save it in the app folder and playing from here.

Example:

func saveAudioFile(url:URL){
    let docUrl: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
    let desURL = docUrl.appendingPathComponent("song.m4a") 

    var task: URLSessionDownloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { [weak self] (URLData, response, error) -> Void in
        do {
            let isFileExists: Bool? = FileManager.default.fileExists(atPath: desURL.path)
            if isFileExists == true{
                print(desURL)
            } else {
                try FileManager.default.copyItem(at: URLData!, to: desURL)
            }

        } catch let error {
            print(error.localizedDescription)
        }
    })

    task.resume()
}
Sagi Shmuel
  • 379
  • 1
  • 6