urlSession:dataTask:didReceive:completionHandler 未在 Xcode8 Swift3 中调用
Posted
技术标签:
【中文标题】urlSession:dataTask:didReceive:completionHandler 未在 Xcode8 Swift3 中调用【英文标题】:urlSession:dataTask:didReceive:completionHandler not called in Xcode8 Swift3 【发布时间】:2016-11-02 11:26:22 【问题描述】:我使用以下代码创建了一个背景 URLSession
对象:
let identifier = /* some background identifier */
let config = URLSessionConfiguration.background(withIdentifier: identifier)
self.session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
我还在委托类中实现了以下URLSessionDataDelegate
方法:
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
// code goes here
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
// code goes here
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
// code goes here
我可以使用以下方法从该会话中成功调用 URLSessionUploadTask
:
let fileURl = /* some file url */
let request = /* some URLRequest */
let task = session.uploadTask(with: request, fromFile: fileUrl)
task.resume()
但由于某种原因,我只收到以下回调:
`urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)`
和
`urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)`.
委托方法:
`urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)`
永远不会被调用。
这是 Xcode8 中的错误还是我遗漏了一些重要的东西? 感谢您的帮助!
【问题讨论】:
它是一个工作代码并且在早期的 xcode 中工作正常吗? 当我在其他两个委托方法上获得委托回调时,代码可以正常工作,我无法在早期的 Xcode 中对此进行测试,因为它们不支持 Swift 3。 【参考方案1】:Apple SDK 直接引用此方法:
/*
* Messages related to the operation of a task that delivers data
* directly to the delegate.
*/
@protocol NSURLSessionDataDelegate <NSURLSessionTaskDelegate>
@optional
/* The task has received a response and no further messages will be
* received until the completion block is called. The disposition
* allows you to cancel a request or to turn a data task into a
* download task. This delegate message is optional - if you do not
* implement it, you can get the response as a property of the task.
*
* This method will not be called for background upload tasks (which cannot be converted to download tasks).
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler;
编辑:为引用添加更多上下文
【讨论】:
您能否提供此直接报价的链接? 更新了我的答案 有趣的是,此信息仅显示在 Obj-C 文档中,而不显示在 Swift 文档中。我会用苹果标记它。非常感谢,匿名的!以上是关于urlSession:dataTask:didReceive:completionHandler 未在 Xcode8 Swift3 中调用的主要内容,如果未能解决你的问题,请参考以下文章