Preventing URLSession redirect in Swift

后端 未结 3 742
迷失自我
迷失自我 2021-02-14 02:59

I need to fetch a redirecting URL but prevent redirection in Swift. From other posts and Apple docs I understand I must implement the delegate method URLS

3条回答
  •  悲哀的现实
    2021-02-14 03:18

    I also found the solution helpful, but I am using Swift 4.2 in my current project.

    So, here is an adapted shorter version of the solution above, that also works with Swift 4.2 and Xcode 10.

    import Foundation
    import PlaygroundSupport
    
    PlaygroundPage.current.needsIndefiniteExecution = true
    
    class MySession: NSObject, URLSessionTaskDelegate {
    
        func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
            completionHandler(nil)
        }
    }
    
    func getDataFromServerWithSuccess(myURL: String, noRedirect: Bool) {
        let myDelegate: MySession? = noRedirect ? MySession() : nil
    
        let session = URLSession(configuration: URLSessionConfiguration.default, delegate: myDelegate, delegateQueue: nil)
        let loadDataTask = session.dataTask(with: URL(string:myURL)!) { (data, response, error) in
    
            // OMITTING ERROR CHECKING FOR BREVITY
            if let data = data {
                if let dataString = String(bytes: data, encoding: .utf8) {
                    print(dataString)
                    if dataString.contains("Bitly") == true {
                        print("success: redirection was prevented")
                    } else {
                        print("failure: redirection went through")
                    }
                }
            }
        }
        loadDataTask.resume()
    }
    
    getDataFromServerWithSuccess(myURL: "http://bitly.com/filmenczer", noRedirect: true)
    

提交回复
热议问题