Alamofire Download Issue

Swift Alamofire Error While Trying to Download File

Add your plist file and Problem solved :) "Swift 4"

<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

Alamofire download issue

Official answer from cnoon (Alamofire member):

Hi @Tulleb,

Apologies for not getting back to you sooner. The example @katopz is
not the same type of request. That example demonstrates how to use a
data task, not a download task. If you don't wish to download the
file, you can instead do the following:

Alamofire.request(url).responseData { response in
guard let data = response.result.value else { return }
let image = UIImage(data: data)
print(image)
}

However, to answer you're original question, you're running into a sandbox permissions issue. We allow you to use the
download APIs without specifying a destination closure for operating
systems like macOS where you can access files outside of your own
sandbox. However, on iOS, you cannot directly access the data of a
file that is outside of your sandbox. That's why you are seeing the
.inputFileReadFailed error.

There are a couple ways you can solve this issue.

Option 1

You can download the data using the request API as shown above which
downloads the image data into memory, not to disk.

Option 2

You can move the file into your sandbox before accessing the data
using a destination closure. Here's an example of how to do that:

let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,
.userDomainMask, true)[0]
let documentsURL = URL(fileURLWithPath: documentsPath, isDirectory: true)
let fileURL = documentsURL.appendingPathComponent("image.png")

return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) }

Alamofire.download("https://httpbin.org/image/png", to:
destination).responseData { response in
debugPrint(response)

if let data = response.result.value {
let image = UIImage(data: data)
print(image)
} else {
print("Data was invalid")
}
}

// Outputs:

// [Request]: https://httpbin.org/image/png // [Response]:
{ URL: https://httpbin.org/image/png
} { status code: 200, headers { // "Access-Control-Allow-Origin" =
"*"; // "Content-Length" = 8090; // "Content-Type" =
"image/png"; // Date = "Sat, 24 Sep 2016 21:34:25 GMT"; //

Server = nginx; // "access-control-allow-credentials" = true; // }
} // [TemporaryURL]:
/private/var/mobile/Containers/Data/Application/25612024-9A05-4ED5-AF3B-A98E22DEAD7A/tmp/CFNetworkDownload_fD9sXf.tmp
// [DestinationURL]:
/var/mobile/Containers/Data/Application/25612024-9A05-4ED5-AF3B-A98E22DEAD7A/Documents/image.png
// [ResumeData]: 0 bytes // [Result]: SUCCESS: 8090 bytes //
[Timeline]: Timeline: { "Request Start Time": 496445664.792, "Initial
Response Time": 496445665.651, "Request Completed Time":
496445665.655, "Serialization Completed Time": 496445665.655, "Latency": 0.860 secs, "Request Duration": 0.863 secs, "Serialization
Duration": 0.000 secs, "Total Duration": 0.864 secs } //
Optional(, {100, 100}) You MUST use a
destination closure if you need to download the file to disk. The
temporary file can only be accessed inside the delegate callback which
is handled internally in Alamofire. If you do not specify a
destination closure on iOS, the temporaryURL will always point to
where the temp file was previously stored, but has been cleaned up.

Summary

So in summary, if you don't need to download the data to disk, then
you want Option 1. If you do want to save the file on disk, then you
want Option 2.

Cheers. /p>

Alamofire download to file system doesn't work

Try to use this method to get documents directory:

try? FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)

And use fileUrl.path instead of fileUrl.absoluteString

Video download using Alamofire is freezing the UI in Swift iOS

Try using below code:

func download(url: String,fileName: String,progressUpdate: ((_ percent: Double) -> Void)? = nil, completion:@escaping (_ success: Bool, _ error: Error?,_ fileUrl: URL?) -> Void) {
let utilityQueue = DispatchQueue.global(qos: .utility)
Alamofire.download(url)
.downloadProgress(queue: utilityQueue) { progress in
DispatchQueue.main.async {
progressUpdate?(progress.fractionCompleted)
}
}
.responseData { response in
if let data = response.result.value {
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent(fileName)
do {
try data.write(to: fileURL, options: .atomic)
completion(true,nil,fileURL)
} catch {
completion(false,error,nil)
}
}
}

}

How to use it:

download(url: "", fileName: "filName", progressUpdate: { (progress) in
print("Progress \(progress)")
}) { (success, error, filePath) in
print("success \(success) error \(error?.localizedDescription ?? "nil") path \(filePath?.absoluteString ?? "nil")")
}

Download pdf file using Alamofire url response error

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.

Alamofire.download by post with parameters not working

I just found that if i change JSONEncoding.default to URLEncoding.default.
It works fine.



Related Topics



Leave a reply



Submit