ios 使用 Alamofire 4.0 (Swift 3) 下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39912905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 10:31:23  来源:igfitidea点击:

Download File Using Alamofire 4.0 (Swift 3)

iosswiftswift3alamofirealamofireimage

提问by JayVDiyk

In older version of Alamofire. This is how I download file

在旧版本的 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);
    }

But now in the new version, my code is completely unusable and there is no similar function in the Alamofire library.

但是现在在新版本中,我的代码完全无法使用,并且Alamofire库中没有类似的功能。

Any ideas please?

请问有什么想法吗?

回答by pedrouan

I used to use this statements:

我曾经使用过这样的语句:

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
    })

For more details read more in Alamofire docs about Migration to 4.0:

有关迁移到 4.0 的更多详细信息,请阅读Alamofire 文档中的更多信息:

回答by Shan Shafiq

There are several enhancements in Alamofire 4. The first of which is the optionality of the destination closure. Now, by default, the destination closure is nil which means the file is not moved anywhere on the file system and the temporary URL is returned.

Alamofire 4 中有几项增强功能。第一个是目的地关闭的可选性。现在,默认情况下,目标闭包为零,这意味着文件不会移动到文件系统上的任何位置,并返回临时 URL。

This is the default execution:-

这是默认执行:-

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

This is my code to download file with Alamofire 4.0 which return destination Url of file:-

这是我使用 Alamofire 4.0 下载文件的代码,它返回文件的目标网址:-

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)
    }
}

回答by Mujahid Latif

Swift 4.0

斯威夫特 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)")
            }
        }

回答by Lazy Ninja

Downloading mp3 file with Alamofire 4.0 Swift 4.x

使用 Alamofire 4.0 Swift 4.x 下载 mp3 文件

Since almost all samples seems to be about downloading an image or a JSON file, it took me hours to find the right solution.
I will share it here hoping it would help others to save some time.

由于几乎所有示例似乎都与下载图像或 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;
}

回答by Giang

Swift 3 Alamofire (4.4.0):

Swift 3 Alamofire (4.4.0):

.plist add key "App Transport Security Settings->Allow Arbitrary Loads->Yes" if you copy and paste code below:

如果您复制并粘贴以下代码,请在 .plist 添加密钥“应用程序传输安全设置->允许任意加载->是”:

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)
    }

回答by Pankaj Jangid

Use this code for download file

使用此代码下载文件

     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!")
            }

        }
    }