我正在尝试在 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")
但仍然只有当应用程序置于前台时下载才会完成。
谢谢!