在重定向之前停止NSURL连接,同时获取重定向网址

时间:2015-07-23 15:49:22

标签: ios swift nsurlconnection nsurlsession

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

我已经尝试在我的代码中使用以下方法,但它们没有被选中:

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

}

1 个答案:

答案 0 :(得分:4)

要停止重定向并获取响应正文,您应该使用<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" /> <div class="container"> <div class="row reorder"> <div id="search_div" class="col-md-3 col-md-push-9"> search form here (this should be on the right on desktop, on top for mobile, and second for tablet) </div> <div id="slideshow_div" class="col-md-9 col-md-pull-3"> slide show here (this should be on the left for desktop, second for mobile and on top for tablet) </div> </div> </div>作为参数调用completionHandler

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

dataTaskWithRequest:completionHandler:

Apple参考: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我不知道它是否有效。

值得添加(约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) } } ):

  

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