未调用 URLSession 委托成功方法,但没有错误
Posted
技术标签:
【中文标题】未调用 URLSession 委托成功方法,但没有错误【英文标题】:URLSession delegate success methods not called, but no error 【发布时间】:2017-01-02 14:25:51 【问题描述】:我正在使用 URLSession dataTask 下载带有 URLSessionDownloadDelegate 作为结果处理程序的文件。但是,永远不会调用 urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
。相反,我得到urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
,错误为零。当使用 completionHandler 方法来执行任务时,一切正常。
这是我的代码:
import UIKit
class ViewController: UIViewController, URLSessionDownloadDelegate
var downloadTask: URLSessionDataTask?
override func viewDidLoad()
super.viewDidLoad()
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
let url = URL(string: "https://unsplash.it/200/300/?random")!
//downloadTask = session.dataTask(with: request)
downloadTask = session.dataTask(with: url)
downloadTask!.resume()
@IBAction func cancelButtonTapped(_ sender: Any)
downloadTask?.cancel()
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?)
print("session: didBecomeInvalidWithError: \(error?.localizedDescription)")
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
print("Your data is here!")
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
let progress = Float(totalBytesWritten / totalBytesExpectedToWrite)
print("Making progress: \(progress)")
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
print("session: task: didCompleteWithError: \(error?.localizedDescription)")
session.finishTasksAndInvalidate()
模拟器输出是
session: task: didCompleteWithError: nil
session: didBecomeInvalidWithError: nil
提前谢谢你。
【问题讨论】:
【参考方案1】:您应该使用URLSessionDownloadTask
而不是URLSessionDataTask
并为URLSessionConfiguration
使用背景,如下所示:
var downloadTask: URLSessionDownloadTask?
var session: URLSession?
override func viewDidLoad()
super.viewDidLoad()
let configuration = URLSessionConfiguration.background(withIdentifier: "backgroundSession")
session = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
let url = URL(string: "https://unsplash.it/200/300/?random")!
downloadTask = session?.downloadTask(with: url)
downloadTask!.resume()
【讨论】:
要么使用正确的委托方法进行数据任务,要么自己积累数据。无论哪种方式。 谢谢,成功了!不过,没有必要为URLSessionConfiguration
使用背景。以上是关于未调用 URLSession 委托成功方法,但没有错误的主要内容,如果未能解决你的问题,请参考以下文章
Swift:UIViewController 实例未从 URLSession 委托方法接收更新
未调用 iOS 13 UIPanGestureRecognizer 选择器
NSURLSessionTaskDelegate 方法 URLSession:task:didCompleteWithError: 从不调用