如果我正确理解我们的问题,你正在寻找一种方式根据此委托函数传回的请求设置任务。
我在过去处理过的方法是用newRequest对象启动一个新任务。就我而言,这是一个下载任务的话,在willPerformHTTPRedirection函数体:那么
let newDownloadTask = session.downloadTaskWithRequest(request)
newDownloadTask.resume()
这个新的任务将启动,并开始委托回调为之前。
UPDATE:
可能做到这一点的最好办法是创建活动的任务和相关网址的字典。我把在操场上一起下 - 你可以根据需要添加相关网址:
import UIKit
import PlaygroundSupport
let currentPage = PlaygroundPage.current
currentPage.needsIndefiniteExecution = true
class downloader : NSObject, URLSessionDelegate, URLSessionDataDelegate {
var session : URLSession!
var tasks : [URLSessionDataTask : String] = [URLSessionDataTask : String]()
func startDownloadWithDelegateHandler() {
self.session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)
let urlString : String = < PUT YOUR URL HERE >
guard let url = URL(string: urlString) else { return }
let request : URLRequest = URLRequest(url: url)
let dataTask : URLSessionDataTask = session.dataTask(with: request)
self.tasks[dataTask] = urlString
dataTask.resume()
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
print("Data received")
print(dataTask.description)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if error != nil {
print(error)
}
else
{
print("Finished")
if let urlString = self.tasks[task as! URLSessionDataTask] {
print(urlString)
}
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
print("Getting redirected")
print(response)
let newDataTask = self.session.dataTask(with: request)
self.tasks[newDataTask] = String(describing: request.url)
print(newDataTask.taskDescription)
newDataTask.resume()
}
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(URLSession.AuthChallengeDisposition.performDefaultHandling, nil)
}
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
if let _ = error {
print(error!)
}
}
}
let myDownloader = downloader()
myDownloader.startDownloadWithDelegateHandler()
我希望你可以按照逻辑,这清除它!
所以你想要在completionHandler中返回的网址? –