Swift下载任务请求文件下载不起作用
我试图通过发送文件的ID从服务器下载文件。我尝试了几件事,但该文件正在下载为CFNetworkDownload.tmp文件。Swift下载任务请求文件下载不起作用
我希望它保存为存在的文件。文件类型可以是PNG,JPEG,PDF,DOCX,PPTX,XLSX。尝试了很多事情,但徒劳无功。我敢肯定它一定是简单的东西,我很想在这里明白
试过以下。在大多数例子中,差异是文件名在URL中。但我发送id并获取文件作为回应。
How to download file in swift?
How To Download Multiple Files Sequentially using NSURLSession downloadTask in Swift
下面是我的代码。
func downloadFile(id : String, fileName : String) -> Void {
let session = URLSession.shared
let url = URL(string: qaDownloadURL+id)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Success: \(statusCode)")
}
do {
// let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
//
// self.savePath = documentsUrl!.absoluteString + "/" + fileName
//
// let fileURL = URL(fileURLWithPath: self.savePath)
//
// let dataFromURL = NSData(contentsOf: tempLocalUrl)
// dataFromURL?.write(to: fileURL, atomically: true)
var documentsDirectory: String?
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
if paths.count > 0
{
documentsDirectory = paths.first!
}
self.savePath = documentsDirectory!// + "/" + fileName
let fileURL = URL(fileURLWithPath: self.savePath)
let dataFromURL = NSData(contentsOf: tempLocalUrl)
dataFromURL?.write(to: fileURL, atomically: true)
// try FileManager.default.copyItem(at: tempLocalUrl, to: fileURL)
DispatchQueue.main.async {
let documentController = UIDocumentInteractionController.init(url: fileURL)
documentController.delegate = self
documentController.presentPreview(animated: true)
}
} catch (let writeError) {
print("error writing file \(self.savePath) : \(writeError)")
}
} else {
print("Failure: %@", error?.localizedDescription);
}
}
task.resume()
}
不能写入数据到它代表一个目录的位置,你需要指定的完整路径,包括文件名。
利用现代URL相关的API,你可以用
do {
let documentFolderURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let fileURL = documentFolderURL.appendingPathComponent(fileName)
try FileManager.default.copyItem(at: tempLocalUrl, to: fileURL)
DispatchQueue.main.async {
let documentController = UIDocumentInteractionController.init(url: fileURL)
documentController.delegate = self
documentController.presentPreview(animated: true)
}
}
更换整个do
块或使用URLSessionDataTask
返回原始数据,而不是将文件下载到一个临时位置,并直接保存Data
例如
let task = session.dataTask(with: request) { (data, response, error) in
guard error == nil else {
print(error!)
return
}
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Success: \(statusCode)")
}
do {
let documentFolderURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let fileURL = documentFolderURL.appendingPathComponent(fileName)
try data!.write(to: fileURL)
DispatchQueue.main.async {
let documentController = UIDocumentInteractionController.init(url: fileURL)
documentController.delegate = self
documentController.presentPreview(animated: true)
}
} catch {
print("error writing file \(fileName) : \(error)")
}
}
task.resume()
如果这不起作用,则错误与其他地方有关。
但为什么它下载tempLocalUrl .tmp文件?任何想法? –
我试过URLSessionDataTask并保存数据,它的工作,你可以多描述一下,这样我就可以接受这个答案 –
@SharanyaKM问题是你使用“POST”方法,而不是“GET”,顺便说一句,你应该只使用一个URL。 URLRequest当你只是想获得一些东西(不是POST) –
你可以这样做:
/**************************************************************************
TAP FOR DOWNLOAD : DOWNLOAD REMOTE DATA AND SAVE TO DOC DIRECTORY
***************************************************************************/
cell.loadingIcon.startAnimating()
let indexPath = self.songTableView.indexPath(for: cell)
let song = filteredList?.object(at: (indexPath?.row)!) as! CKSong
let songURL = NSURL(string : song.url as! String)
let downloadTask : URLSessionDownloadTask = self.downloadsSession.downloadTask(with: songURL as! URL) { (location, response, error) in
if (error == nil) {
let time = NSNumber(value:(NSDate().timeIntervalSince1970 * 1000))
let fileName = NSString(format:"%@_music.mp3",time)
let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent(fileName as String)
do {
try FileManager.default.copyItem(at: location!, to: destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
print("DOWNLOAD FINISHED \(location)")
print("DOWNLOAD FINISHED \(destinationFileUrl)")
song.localURL = destinationFileUrl.path as NSString?
}
DispatchQueue.main.async {
cell.playButton.isEnabled = (song.localURL != nil)
cell.loadingIcon.stopAnimating()
}
}
downloadTask.resume()
}
//====================================================================================================================================
// SONG DOWNLOAD TASK : NSURLSESSION
//====================================================================================================================================
lazy var downloadsSession: URLSession = {
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
return session
}()
希望这有助于。
没有...这不工作... –
是的,我刚刚也试过。不起作用:( –
问题是你使用“POST”方法而不是“GET”。顺便说一句,你应该只使用一个URL。当你只想获得某些东西(不是POST)时不需要使用URLRequest –
顺便说一句应该帮助http://*.com/a/27643660/2303865 –