如果我正確理解我們的問題,你正在尋找一種方式根據此委託函數傳回的請求設置任務。
我在過去處理過的方法是用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中返回的網址? –