我正在尝试使用swift和iOS 8中的以下代码实现NSURLSessionDownloadTask:

var dlURL = NSURL(string: http://thedownloadurl")

var defaultConfigObject = NSURLSessionConfiguration.defaultSessionConfiguration()
defaultConfigObject.timeoutIntervalForRequest = 300.0
defaultConfigObject.allowsCellularAccess = true

var defaultSession = NSURLSession(configuration: defaultConfigObject, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
var downloadTask = defaultSession.downloadTaskWithURL(dlURL)
downloadTask.resume()

我捕获响应:

func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didFinishDownloadingToURL location: NSURL!) {
    println("Downloaded to location: \(location)")

    let str = NSString(contentsOfURL: location, encoding: NSUTF8StringEncoding, error: nil)
    println(str)
    var localNotify = UILocalNotification()
    localNotify.alertBody = "Download completed"
    localNotify.soundName = UILocalNotificationDefaultSoundName
    UIApplication.sharedApplication().presentLocalNotificationNow(localNotify)
}

当我运行时,这是模拟器,所有工作都按预期工作,它完成下载,显示在屏幕上的漂亮通知,即使设备被锁定屏幕 . 但是,当我在iPhone 4s上测试它时,只有在我将应用程序放回前台后才能完成下载 . 关于为什么会这样的任何想法?

编辑:为了完整,我也尝试过

var defaultConfigObject = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("uniqueIdentifier")

但是,只有当应用程序处于前台时,下载才会完成 .

谢谢!