1
votes

I want to download Pdf file url i used this code:

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

and in the 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)
            }
        }
    }
}

when i call downloadPdf method for the first time it downloaded the file successfully but i got this error:

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: تعذرت قراءة البيانات نظرًا لأن تنسيقها غير صحيح.

if call the method again i got this 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" نظرًا لوجود عنصر بنفس الاسم.

this error because there a file in the same directory with the same name, i tried to use responseString instead of responseJSON but it doesn't solve my problem, what should i do ?

1
PDF is not JSON, just process the raw Data, .responseJSON is wrong.vadian

1 Answers

6
votes

There are few mistakes in your code :

  1. It is a Data task as not JSON task as pointed out by Vadian.

Change your download function to this :

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. You error :

    Error Domain=NSPOSIXErrorDomain Code=17 "File exists"

clearly tells that there is already a file at that filePath. So This code will remove previous file if there is any.