在 Swift 3 中使用 Alamofire 4 中的 SessionManager 下载音频文件

Posted

技术标签:

【中文标题】在 Swift 3 中使用 Alamofire 4 中的 SessionManager 下载音频文件【英文标题】:Download a Audio file using SessionManager in Alamofire 4 in Swift 3 【发布时间】:2016-10-15 09:24:00 【问题描述】:

在 alomofire 3.5 中,以下代码运行良好

self.sessionManager.download(.GET, AppConstants.musicFileURL + musicFilename, destination:  (url, response) -> NSURL in
        let fileManager = NSFileManager.defaultManager()
        let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
        let fileUrl = directoryURL.URLByAppendingPathComponent(musicFilename)
        return fileUrl
      )
    .progress  bytesRead, totalBytesRead, totalBytesExpectedToRead in
      self.percentageDownloaded[exhibitId]![artworkId] = (Double(totalBytesRead) ,Double(totalBytesExpectedToRead))
      let meanPercentageDone = self.calculatePercentageDoneForExhibit(exhibitId, artworkArray: self.artworkArray)
      let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
      appDelegate.notifyDownloadProgress(meanPercentageDone)
    
    .response  _, _, _, _ in

      NSLog("Completed downloading audio file,%@ , for artwork %@", musicFilename, artworkId)
      if DataManager.saveMusicDownloadComplete(artworkId, exhibitId: exhibitId)
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        appDelegate.notifyMusicDownloadsComplete(exhibitId)
        self.percentageDownloaded[exhibitId] = [String: (Double, Double)?]()
        NSLog("when all music files have been downloaded")
      
  

如何将上述代码迁移到 Alamofire 4。在迁移文档中看不到任何 cmets。

【问题讨论】:

试试看:raywenderlich.com/121540/alamofire-tutorial-getting-started @JamshedAlam,本教程适用于 Swift 2.2。可悲的是不是 Swift 3 可以转成swift 3 @JamshedAlam,是的,我做到了 【参考方案1】:
let destination: DownloadRequest.DownloadFileDestination =  _, _ in
    var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

    documentsURL.appendPathComponent(musicFilename)
    return (documentsURL, [.removePreviousFile])


Alamofire.download(AppConstants.musicFileURL + musicFilename, to: destination)


    .downloadProgress  progress in
        print("Download Progress: \(progress.fractionCompleted)")
    

    .responseString(completionHandler:  (response) in
        print("Success: \(response.result.isSuccess)")
        print("Response String: \(response.result.value)")

    )

我更改为Alamofire.download,而不是在SessionManager 中下载

【讨论】:

如果我想使用 SessionManager 来获得后台功能,我该如何让它工作? github.com/Alamofire/Alamofire/blob/master/Documentation/…看看

以上是关于在 Swift 3 中使用 Alamofire 4 中的 SessionManager 下载音频文件的主要内容,如果未能解决你的问题,请参考以下文章