2016-10-07 3 views
7

In älteren Versionen von Alamofire. Dies ist, wie ich Datei herunterladenDatei herunterladen mit Alamofire 4.0 (Swift 3)

let destinationPath = Alamofire.Request.suggestedDownloadDestination(directory: .documentDirectory, domain: .userDomainMask); 

    Alamofire.download(.GET, urlString, destination: destinationPath) 
     .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in 
//    print(totalBytesRead) 
     } 
     .response { request, response, _, error in 

      let downloadedFilePath = destinationPath(URL(string: "")!, response!); 

      NSUserDefaultsHelper.saveURL(downloadedFilePath, key: urlString); 

      completion(downloadedFilePath, true); 
    } 

Aber jetzt in der neuen Version, mein Code ist völlig unbrauchbar und es gibt keine ähnliche Funktion in der Alamofire Bibliothek.

Irgendwelche Ideen bitte?

+3

Wenn ich Google 'Datei herunterladen Mit Alamofire 4.0 (Swift 3)', ich einen Link zu Alamofire offizieller Dokumentation erhalten, die ein [Beispiel] hat (https://github.com/Alamofire/Alamofire#downloading- Daten in eine Datei) zum Herunterladen einer Datei. Ist das nicht nützlich? –

Antwort

21

Ich habe diese Aussagen zu verwenden:

let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory) 

Alamofire.download(
    url, 
    method: .get, 
    parameters: parameters, 
    encoding: JSONEncoding.default, 
    headers: nil, 
    to: destination).downloadProgress(closure: { (progress) in 
     //progress closure 
    }).response(completionHandler: { (DefaultDownloadResponse) in 
     //here you able to access the DefaultDownloadResponse 
     //result closure 
    }) 

Für weitere Informationen lesen Sie mehr in Alamofire docs about Migration to 4.0:

+0

Der Code-Block in der Antwort ist DefaultDownloadResponse, ich habe Probleme beim Abrufen der endgültigen 'DownloadedFilePath' – JayVDiyk

+0

Der eigentliche heruntergeladene Dateipfad ist 'Ziel + NameOfTheFile', nicht wahr? – pedrouan

+0

Ja, aber wenn Sie sich meinen Code ansehen, wird der Dateiname automatisch von Alamofire generiert. Aus diesem Grund habe ich die Funktion destinationPath verwendet, um den vollständigen Pfad zu erhalten. – JayVDiyk

6

Es gibt mehrere Erweiterungen in Alamofire 4. Die erste davon ist die Optionalität der Ziel Schließung. Jetzt ist die Zielschließung standardmäßig null, was bedeutet, dass die Datei nirgendwo im Dateisystem verschoben wird und die temporäre URL zurückgegeben wird.

Dies ist die Standardausführung: -

Alamofire.download(urlString).responseData { response in 
    print("Temporary URL: \(response.temporaryURL)") 
} 

Dies ist mein Code-Datei mit Alamofire 4.0, die Ziel-URL Datei zurück zum Download: -

let destination: DownloadRequest.DownloadFileDestination = { _, _ in 
     var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] 
     documentsURL.appendPathComponent("duck.png") 
     return (documentsURL, [.removePreviousFile]) 
    } 

    Alamofire.download(url, to: destination).responseData { response in 
    if let destinationUrl = response.destinationURL ? { 
     completionHandler(destinationUrl) 
    } 
} 
+0

warum Sie 'documentsURL, [.removePreviousFile]' verwenden –

3

Swift 3 Alamofire (4.4.0):

.plist fügen Sie den Schlüssel "App Transport Sicherheitseinstellungen -> Arbitrary Loads -> Ja", wenn Sie Code kopieren und einfügen:

import Alamofire 

    let destination = DownloadRequest.suggestedDownloadDestination() 

    Alamofire.download("http://zmp3-mp3-lossless-te-zmp3-bdhcm-1.zadn.vn/151e407bb43f5d61042e/1223048424027738068?key=f-zMo3GZKlhVibnvGMsMuQ&expires=1495726053&filename=See%20You%20Again%20-%20Wiz%20Khalifa%20Charlie%20Puth%20(NhacPro.net).flac", to: destination).downloadProgress(queue: DispatchQueue.global(qos: .utility)) { (progress) in 
     print("Progress: \(progress.fractionCompleted)") 
    } .validate().responseData { (response) in 
     print(response.destinationURL!.lastPathComponent) 
    } 
1

Herunterladen von MP3-Datei mit Alamofire 4.0 Swift 4.x

Da fast alle Proben scheint über das Herunterladen eines Bildes oder JSON-Datei zu sein, es hat mich Stunden, um die richtige Lösung zu finden.
Ich werde es hier teilen hoffe, es würde anderen helfen, etwas Zeit zu sparen.

func startDownload(audioUrl:String) -> Void { 
    let fileUrl = self.getSaveFileUrl(fileName: audioUrl) 
    let destination: DownloadRequest.DownloadFileDestination = { _, _ in 
     return (fileUrl, [.removePreviousFile, .createIntermediateDirectories]) 
    } 

    Alamofire.download(audioUrl, to:destination) 
     .downloadProgress { (progress) in 
      self.progressLabel.text = (String)(progress.fractionCompleted) 
     } 
     .responseData { (data) in 
      self.progressLabel.text = "Completed!" 
    } 
} 

func getSaveFileUrl(fileName: String) -> URL { 
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] 
    let nameUrl = URL(string: fileName) 
    let fileURL = documentsURL.appendingPathComponent((nameUrl?.lastPathComponent)!) 
    NSLog(fileURL.absoluteString) 
    return fileURL; 
} 
Verwandte Themen