Preventing URLSession redirect in Swift

后端 未结 3 734
迷失自我
迷失自我 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:36

    Minor adjustments to the solutions proposed above. This works with Swift 2 in XCode 7.

    import UIKit
    import Foundation
    import XCPlayground
    
    XCPSetExecutionShouldContinueIndefinitely(true)
    
    class MySession: NSObject, NSURLSessionDelegate {
    
        // to prevent redirection
        func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest!) -> Void) {
        completionHandler(nil)
        }
    
        // fetch data from URL with NSURLSession
        class func getDataFromServerWithSuccess(myURL: String, noRedirect: Bool, success: (response: String!) -> Void) {
        var myDelegate: MySession? = nil
        if noRedirect {
            myDelegate = MySession()
        }
        let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: myDelegate, delegateQueue: nil)
        let loadDataTask = session.dataTaskWithURL(NSURL(string: myURL)!) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
            // OMITTING ERROR CHECKING FOR BREVITY
            success(response: NSString(data: data!, encoding: NSASCIIStringEncoding) as! String)
        }
        loadDataTask.resume()
        }
    
        // extract data from redirect
        class func getRedirectionInfo(url: String) {
        getDataFromServerWithSuccess(url, noRedirect: true) {(data) -> Void in
            if let html = data {
                if html.rangeOfString("\nBitly", options: .RegularExpressionSearch) != nil {
                    print("success: redirection was prevented")
                } else {
                    print("failure: redirection went through")
                }
            }
        }
        }
    }
    
    MySession.getRedirectionInfo("http://bit.ly/filmenczer")
    

提交回复
热议问题