只要您的应用程序在前台,Devran和djunod的解决方案都可以正常工作。但是,如果您在下载期间切换到另一个应用程序,则会失败。我的文件大小约为10 MB,下载需要一些时间。因此,我需要我的下载功能即使应用程序进入后台也能正常工作。
请注意,我已经在“Capabilities”中打开了“Background Modes / Background Fetch”。
由于不支持completionhandler,所以该解决方案未封装。很抱歉。
--Swift 2.3--
import Foundation
class Downloader : NSObject, NSURLSessionDownloadDelegate
{
var url : NSURL?
var yourOwnObject : NSObject?
init(yourOwnObject : NSObject)
{
self.yourOwnObject = yourOwnObject
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL)
{
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first
let destinationUrl = documentsUrl!.URLByAppendingPathComponent(url!.lastPathComponent!)
let dataFromURL = NSData(contentsOfURL: location)
dataFromURL?.writeToURL(destinationUrl, atomically: true)
yourOwnObject!.callWhatIsNeeded()
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
{
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?)
{
if(error != nil)
{
print("Download completed with error: \(error!.localizedDescription)");
}
}
func download(url: NSURL)
{
self.url = url
let sessionConfig = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(url.absoluteString)
let session = NSURLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
let task = session.downloadTaskWithURL(url)
task.resume()
}
}
这里是如何调用 --Swift 2.3-- 的方法
let url = NSURL(string: "http://company.com/file.txt")
Downloader(yourOwnObject).download(url!)
--Swift 3--
class Downloader : NSObject, URLSessionDownloadDelegate {
var url : URL?
var yourOwnObject : NSObject?
init(_ yourOwnObject : NSObject)
{
self.yourOwnObject = yourOwnObject
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
{
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let destinationUrl = documentsUrl!.appendingPathComponent(url!.lastPathComponent)
let dataFromURL = NSData(contentsOf: location)
dataFromURL?.write(to: destinationUrl, atomically: true)
yourOwnObject!.callWhatIsNeeded()
}
private func URLSession(session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
{
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
{
if(error != nil)
{
print("Download completed with error: \(error!.localizedDescription)");
}
}
func download(url: URL)
{
self.url = url
let sessionConfig = URLSessionConfiguration.background(withIdentifier: url.absoluteString)
let session = Foundation.URLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
let task = session.downloadTask(with: url)
task.resume()
}}
以下是如何在Swift 3中调用的方法:
let url = URL(string: "http://company.com/file.txt")
Downloader(yourOwnObject).download(url!)
data
包含整个二进制PDF文件。要返回data
的内容,只需写入println(data)
。如果想学习如何在iOS上保存文件,请看:https://github.com/sketchytech/FileSave (也有Swift版本)。 - Devran Cosmo Uenal