проблема с загрузкой и сохранением аудиофайла в функции didSelectRowAt - PullRequest
0 голосов
/ 04 августа 2020

Я работаю над приложением, которое загружает аудиофайл с сервера, сохраняет его на устройстве, а затем снова нажимаю, чтобы воспроизвести его, но проблема в том, что каждый раз, когда я нажимаю на ячейку, файл загружается повторно !!

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedCellIndex = indexPath
    
    let cell = self.audioTableView.cellForRow(at: indexPath) as! AudioTableViewCell
    let audioUrl = audio[indexPath.row].audioUrl
    configure(with: audioUrl, indexPath: indexPath, cell: cell)
}


func configure(with myUrl : String, indexPath: IndexPath, cell: AudioTableViewCell) {
    downloadAndSaveAudioFile(urlString: myUrl, index: indexPath, cell: cell)
}

func downloadAndSaveAudioFile(urlString: String, index: IndexPath, cell: AudioTableViewCell) {
    guard let audioUrl = URL(string: urlString) else {return}

    let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    
    let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
    
    // every time i tapped the cell, validation of this condition fails

    if FileManager.default.fileExists(atPath: destinationUrl.path) { 
        print("The file already exists at path")
    } else {
        
        let config = URLSessionConfiguration.default
        let operationQueue = OperationQueue()
        let urlSession = URLSession(configuration: config, delegate: self, delegateQueue: operationQueue)
        let downloadTask = urlSession.downloadTask(with: audioUrl)
        downloadTask.resume()
        
    }
    
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    let percentege = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
            DispatchQueue.main.async {
                self.myProg = percentege * 100
                let cell = self.audioTableView.cellForRow(at: self.selectedCellIndex!) as! AudioTableViewCell
                cell.progressV.progress = percentege
            }
    
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {

    print("\(expectedTotalBytes)")
}


func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    print("did finish downloading To...")
    
    let cell = self.audioTableView.cellForRow(at: self.selectedCellIndex!) as! AudioTableViewCell
    cell.img.image = UIImage(systemName: "play.fill")
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
    print("completed: error: \(String(describing: error))")
}

Есть ли какой-нибудь совет или объяснение метода?

1 Ответ

1 голос
/ 04 августа 2020

Вы еще не переместили загруженный файл в destination path. Вот почему проверка fileExists всегда терпела неудачу.

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    print("did finish downloading To...")
    
    let cell = self.audioTableView.cellForRow(at: self.selectedCellIndex!) as! AudioTableViewCell
    cell.img.image = UIImage(systemName: "play.fill")
    
    // After downloading your file, you need to move it to your destination url
    do {
        try FileManager.default.moveItem(at: location, to: `your new destination`)
        print("File moved to documents folder")
    } catch {
        print("Error when moving file")
    }

}

Вот пример: https://mobikul.com/play-audio-file-save-document-directory-ios-swift/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...