Ecco metodo completo per scaricare file in destinazione con il progresso
// MARK: metodi di download
func downloadFile(reqType : RequestType, urlParam: String,completionHandler: (Double?, NSError?) -> Void) {
let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
var downloadPath = documentsPath.URLByAppendingPathComponent("downloads")
var isDirectory: ObjCBool = false
if NSFileManager.defaultManager().fileExistsAtPath(downloadPath.path!, isDirectory: &isDirectory) {
if(!isDirectory){
do {
try NSFileManager.defaultManager().createDirectoryAtPath(downloadPath.path!, withIntermediateDirectories: true, attributes: nil)
}catch {
NSLog("Unable to create directory ")
}
}
}else{
do {
try NSFileManager.defaultManager().createDirectoryAtPath(downloadPath.path!, withIntermediateDirectories: true, attributes: nil)
}catch {
NSLog("Unable to create directory ")
}
}
//get the url from GTM
let urlString = self.getRequestedUrlFromIdentifier(reqType, param: urlParam)
let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
Alamofire.download(.GET, urlString, destination: { (temporaryURL, response) in
let pathComponent = response.suggestedFilename
downloadPath = downloadPath.URLByAppendingPathComponent(pathComponent!)
if NSFileManager.defaultManager().fileExistsAtPath(downloadPath.path!) {
do{
try NSFileManager.defaultManager().removeItemAtPath(downloadPath.path!)
}catch {
}
}
return downloadPath
}) .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
print(totalBytesRead)
// This closure is NOT called on the main queue for performance
// reasons. To update your ui, dispatch to the main queue.
dispatch_async(dispatch_get_main_queue()) {
print("Total bytes read on main queue: \(totalBytesRead)")
}
}
.response { request, response, _, error in
print(response)
let originalPath = destination(NSURL(string: "")!, response!)
if let error = error {
completionHandler(500000.1 , nil)
print("Failed with error: \(error)")
} else {
completionHandler(500000.0 , nil)
print("Downloaded file successfully \(downloadPath)")
}
}
}
fonte
2016-05-26 08:03:06
Stavo per fare la stessa domanda come ho lo stesso problema in questo momento! – dburgmann