ios - 使用 Alamofire url 响应错误下载 pdf 文件

标签 ios swift pdf alamofire

我想下载 Pdf 文件 url 我使用了这段代码:

class func downloadPdf(pdfReport: String, completion: @escaping (_ error: Error?, _ success: Bool,_ value: String) -> Void) {

    let downloadUrl: String = URLs.pdfFileUrl + pdfReport
    let destination = DownloadRequest.suggestedDownloadDestination()

    print(downloadUrl, destination)
    Alamofire.download(downloadUrl, method: .get, parameters: nil, encoding: JSONEncoding.default, to: destination).responseJSON { response in

        switch response.result {
        case .failure(let error):
            print("error: ", error)
            print(error.localizedDescription)
            completion(error, false, "")
        case .success(let value):
            let json = JSON(value)
            print(json)
            print("successss")
            completion(nil, true, "")
        }
    }
}

在 View Controller 中:

func downloadPdf() {
    KRProgressHUD.show(withMessage: NSLocalizedString("wait", comment: "wait"))
    API.downloadPdf(pdfReport: self.report.report){ (error: Error?, success: Bool, result: String) in
        if success {
            KRProgressHUD.dismiss()
        } else {
            KRProgressHUD.dismiss()
            if (!Connectivity.isConnectedToNetwork()){
                Toast.toast(messsage: NSLocalizedString("no internet", comment: "no internet"), view: self.view)
            } else {
                Toast.toast(messsage: NSLocalizedString("error occured", comment: "error occured"), view: self.view)
            }
        }
    }
}

当我第一次调用 downloadPdf 方法时,它成功下载了文件,但出现了这个错误:

https://madrasty.dev.ibtdi.work/public/reports/15287105135b1e4571f2596-new.pdf (Function) error: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})) JSON could not be serialized because of error: تعذرت قراءة البيانات نظرًا لأن تنسيقها غير صحيح.

如果再次调用该方法,我会收到此错误:

error: Error Domain=NSCocoaErrorDomain Code=516 "تعذر نقل "CFNetworkDownload_WBV95z.tmp" إلى "Documents" نظرًا لوجود عنصر بنفس الاسم." UserInfo={NSSourceFilePathErrorKey=/Users/ibtdi/Library/Developer/CoreSimulator/Devices/10CB5B13-42C2-4646-934C-67FD33C948C5/data/Containers/Data/Application/F894940C-0D55-4953-A9FA-E852C1C4B440/tmp/CFNetworkDownload_WBV95z.tmp, NSUserStringVariant=( Move ), NSDestinationFilePath=/Users/ibtdi/Library/Developer/CoreSimulator/Devices/10CB5B13-42C2-4646-934C-67FD33C948C5/data/Containers/Data/Application/F894940C-0D55-4953-A9FA-E852C1C4B440/Documents/15287105135b1e4571f2596-new.pdf, NSFilePath=/Users/ibtdi/Library/Developer/CoreSimulator/Devices/10CB5B13-42C2-4646-934C-67FD33C948C5/data/Containers/Data/Application/F894940C-0D55-4953-A9FA-E852C1C4B440/tmp/CFNetworkDownload_WBV95z.tmp, NSUnderlyingError=0x604000254460 {Error Domain=NSPOSIXErrorDomain Code=17 "File exists"}} تعذر نقل "CFNetworkDownload_WBV95z.tmp" إلى "Documents" نظرًا لوجود عنصر بنفس الاسم.

这个错误是因为在同一个目录下有一个同名的文件, 我尝试使用 responseString 而不是 responseJSON 但它没有解决我的问题,我该怎么办?

最佳答案

您的代码中几乎没有错误:

  1. 这是一个 Data 任务,而不是 Vadian 指出的 JSON 任务。

将您的下载功能更改为:

func downloadPdf(pdfReport: String, uniqueName: String, completionHandler:@escaping(String, Bool)->()){

    let downloadUrl: String = URLs.pdfFileUrl + pdfReport
    let destinationPath: DownloadRequest.DownloadFileDestination = { _, _ in
        let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0];
        let fileURL = documentsURL.appendingPathComponent("\(uniqueName).pdf")
        return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
    }
    print(downloadUrl)
    Alamofire.download(downloadUrl, to: destinationPath)
        .downloadProgress { progress in

        }
        .responseData { response in
            print("response: \(response)")
            switch response.result{
            case .success:
                if response.destinationURL != nil, let filePath = response.destinationURL?.absoluteString {
                    completionHandler(filePath, true)
                }
                break
            case .failure:
                completionHandler("", false)
                break
            }

    }
}
  1. 你的错误:

    Error Domain=NSPOSIXErrorDomain Code=17 “文件存在”

清楚地表明该文件路径中已经有一个文件。所以这段代码将删除以前的文件(如果有的话)。

关于ios - 使用 Alamofire url 响应错误下载 pdf 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50796802/

相关文章:

ios - AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)

ios - RubyMotion 未加载 AudioToolbox 框架

ios - 在 Git 中接收对象太慢

html - 在线所见即所得的 PDF 编辑器

ios - CLLocation 接受大于或小于其最小值和最大值的经度和纬度

ios - 如何为页面 View Controller 提供 "Cover Vertical"过渡样式

ios - 如何在 UIView 动画期间更新 ImageView

arrays - 在参数请求中传递字符串数组 - swift 5

java - iText 选择保存 PDF 的路径

jquery - 如何避免打印为 pdf 时固定 div 的重叠?