【问题标题】:Stopping NSURL Connection before redirect, while getting the redirect URL在重定向之前停止 NSURL 连接,同时获取重定向 URL
【发布时间】:2015-07-23 15:49:21
【问题描述】:

我正在尝试取回 url 的响应正文,该响应正文重定向到另一个无效的 url。我也想停止重定向,因为它会使我的应用崩溃。

我曾尝试在我的代码中使用以下方法,但没有被采纳:

func URLSession(_ session: NSURLSession,
    dataTask dataTask: NSURLSessionDataTask,
    didReceiveResponse response: NSURLResponse,
    completionHandler completionHandler: (NSURLSessionResponseDisposition) -> Void) {
        print("Did you get here?")
}

func URLSession(_ session: NSURLSession,
    task task: NSURLSessionTask,
    didCompleteWithError error: NSError?) {
        print("How about here?")
}

func URLSession(_ session: NSURLSession,
    task task: NSURLSessionTask,
    willPerformHTTPRedirection response: NSHTTPURLResponse,
    newRequest request: NSURLRequest,
    completionHandler completionHandler: (NSURLRequest?) -> Void) {
        print("Maybe here?")
}

func URLSession(_ session: NSURLSession,
    didBecomeInvalidWithError error: NSError?) {
        print("Did you find an error?")
}

对我能做什么有什么想法吗?

编辑:所以,这是我拥有的更新代码,使用 XCode 7 时不会出现错误:

class Example: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate {


override init() {
    super.init()

    let mySession = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue.mainQueue())

    // Put your handler as the second parameter.
    let data = try!mySession.dataTaskWithURL(NSURL(string: "http://www.google.com")!, completionHandler: myHandler)

    data!.resume()
}

// Create your handler with the following signature, and read the response body.
func myHandler(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void {

    // In this case the “encoding” is NSASCIIStringEnconding. It depends on the website.
    let responseBody = NSString(data: data!, encoding: NSASCIIStringEncoding)

    print(responseBody)
}



// Handles redirection
private func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest!) -> Void) {

    // Stops the redirection, and returns (internally) the response body.
    completionHandler(nil)
}

}

【问题讨论】:

    标签: ios swift nsurlconnection nsurlsession


    【解决方案1】:

    要停止重定向并获取响应正文,您应该调用 completionHandler 并使用 nil 作为参数。

    停止重定向后,当您使用dataTaskWithURL:completionHandler:(也可以是dataTaskWithRequest:completionHandler:)创建HTTP Get 请求时,URLSession 将调用您指定的处理程序。然后在处理程序中你得到响应体。示例:

    import Foundation
    
    class Example: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate {
    
    
        override init() {
            super.init()
    
            let mySession = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue.mainQueue())
    
            // Put your handler as the second parameter.
            let data = mySession.dataTaskWithURL(NSURL(string: "http://www.google.com")!, completionHandler: myHandler)
    
            data.resume()
        }
    
        // Create your handler with the following signature, and read the response body.
        func myHandler(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void {
    
            // In this case the “encoding” is NSASCIIStringEnconding. It depends on the website.
            let responseBody = NSString(data: data, encoding: NSASCIIStringEncoding)
    
            println(responseBody)
        }
    
    
    
        // Handles redirection
        func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest!) -> Void) {
    
            // Stops the redirection, and returns (internally) the response body.
            completionHandler(nil)
        }
    }
    

    苹果参考:https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionTaskDelegate_protocol/index.html#//apple_ref/occ/intfm/NSURLSessionTaskDelegate/URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler

    我知道它适用于 HTTP 302 代码,但对于 301(永久移动)或 308 等其他代码,我不知道它是否有效。

    值得补充(关于URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:):

    仅在默认和临时会话中的任务调用此方法。后台会话中的任务会自动遵循重定向。

    【讨论】:

    • 我不得不更改方法 URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:),因为它给了我错误,现在它不喜欢 completionHandler 有一个 nil 参数。
    • 它给出了什么错误?我刚刚用 XCode 6.4 和 iOS 8.4 测试了上面的代码,效果很好。
    • 我正在使用 XCode 7,我得到:cannot invoke 'dataTaskWithURL' with an argument list of type '(NSURL, completionHandler: (NSData!, response: NSURLResponse!, error: NSError!) -> Void)',以及 Objective-C method 'URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:' provided by method 'URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)' conflicts with optional requirement method 'URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)' in protocol 'NSURLSessionTaskDelegate'
    • 我可以通过将函数设为私有来摆脱第二个错误。
    • 好吧,我能想到的是:文件是 swift 文件吗?同一个类中有两个URLSession(:task:willPerformHTTPRedirection:newRequest:completionHandler:) 函数吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-29
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    相关资源
    最近更新 更多