Загрузка Файла С Помощью Alamofire 4.0 (Swift 3)
в старой версии Alamofire. Вот как я загружаю файл
    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);
    }
но теперь в новой версии мой код полностью непригоден для использования, и в библиотеке Alamofire нет подобной функции.
любые идеи, пожалуйста?
6 ответов
я использовал эти операторы:
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
    })
Подробнее читайте в Alamofire документы о миграции в 4.0:
в Alamofire 4 есть несколько улучшений. Первым из которых является опциональность закрытия пункта назначения. Теперь по умолчанию закрытие назначения равно nil, что означает, что файл не перемещается в любом месте файловой системы и возвращается временный URL.
это выполнение по умолчанию:-
Alamofire.download(urlString).responseData { response in
    print("Temporary URL: \(response.temporaryURL)")
}
Это мой код для загрузки файла с Alamofire 4.0, который возвращает Url-адрес назначения файла: -
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)
    }
}
Swift 4.0
 let destination: DownloadRequest.DownloadFileDestination = { _, _ in
            var documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            documentsURL.appendPathComponent("file.csv")
            return (documentsURL, [.removePreviousFile])
        }
        Alamofire.download(url, to: destination).responseData { response in
            if let destinationUrl = response.destinationURL {
               print("destinationUrl \(destinationUrl.absoluteURL)")
            }
        }
Swift 3 Alamofire (4.4.0):
.plist добавить ключ "App Transport Security Settings - >разрешить произвольные нагрузки - >да", если вы копируете и вставляете код ниже:
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)
    }
загрузка mp3-файла с Alamofire 4.0 Swift 4.x
поскольку почти все образцы, похоже, о загрузке изображения или файла JSON, мне потребовалось несколько часов, чтобы найти правильное решение.
Я поделюсь его здесь, надеясь, что это поможет другим сэкономить время.
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;
}
используйте этот код для скачивания файла
     let fileManager = FileManager.default
     let directoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
    Alamofire.request(\(downloadUrl)).downloadProgress(closure : { (progress) in
        print(progress.fractionCompleted)
    }).responseData{ (response) in
        print(response)
        print(response.result.value!)
        print(response.result.description)
           let randomString = NSUUID().uuidString
        if let data = response.result.value {
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
            let videoURL = documentsURL.appendingPathComponent("\(randomString)")
            do {
                try data.write(to: videoURL)
            } catch {
                print("Something went wrong!")
            }
        }
    }