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

时间:2016-10-15 09:24:00

标签: ios swift3 alamofire ios10

在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.无法在迁移文档中看到任何注释。

1 个答案:

答案 0 :(得分:0)

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

下载