如何在swift中将最终url返回给委托人?

时间:2016-09-19 07:19:11

标签: ios swift

我知道如何捕获重定向网址的最终网址,但我不知道如何将最终网址返回给委托人。

那是

func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
         request.url //send this final url back so that I can call it in another delegate
    }

在我们获得最终网址后,我想将最终网址传递给另一个委托功能

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
       thenDoSomething()
        }
    }

2 个答案:

答案 0 :(得分:3)

如果我正确理解了我们的问题,那么您正在寻找一种基于此委托函数传回的请求来设置任务的方法。

我过去处理这个问题的方法是使用newRequest对象启动一个新任务。在我的情况下,这是一个下载任务,所以,在willPerformHTTPRedirection函数的主体中:

let newDownloadTask = session.downloadTaskWithRequest(request)
newDownloadTask.resume()

然后,这个新任务将像以前一样启动并开始进行委托回调。

更新:

执行此操作的最佳方法可能是创建包含活动任务和相关URL的字典。我在操场上将以下内容放在一起 - 您可以根据需要添加相关的URL:

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()

我希望你能按照这个逻辑来解决这个问题!

答案 1 :(得分:-1)

您应该在->方法和func的右侧添加return request.url。 如下所示: func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) -> NSURL { return request.url //send this final url back so that I can call it in another delegate }