gpt4 book ai didi

ios - 在 Swift 中防止 URLSession 重定向

转载 作者:IT王子 更新时间:2023-10-29 05:52:06 24 4
gpt4 key购买 nike

我需要在 Swift 中获取重定向 URL 但阻止重定向。从其他帖子和 Apple 文档我了解到我必须实现委托(delegate)方法 URLSession(session:, task:, willPerformHTTPRedirection response:, request:, completionHandler:) 并通过完成关闭。但我无法 swift 找到示例,也找不到正确的方法。下面的代码重现了我在 Playground 上的问题:委托(delegate)似乎没有被执行。

import Foundation
import XCPlayground

XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)

class MySession: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate {

// trying to follow instructions at https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionTaskDelegate_protocol/index.html#//apple_ref/occ/intfm/NSURLSessionTaskDelegate/URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:
// to prevent redirection -- DOES NOT SEEM TO GET CALLED
func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest!) -> Void) {
println("in URLSession delegate") // NEVER PRINTS
completionHandler(nil) // NO EFFECT
}

// fetch data from URL with NSURLSession
class func getDataFromServerWithSuccess(myURL: String, success: (response: String!) -> Void) {
var session = NSURLSession.sharedSession()
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) {(data) -> Void in
if let html = data {
if html.rangeOfString("<html><head><title>Object moved</title>", options: .RegularExpressionSearch) != nil {
println("success: redirection was prevented") // SHOULD PRINT THIS
} else {
println("failure: redirection went through") // INSTEAD PRINTS THIS
}
}
}
}
}

MySession.getRedirectionInfo("http://bit.ly/filmenczer") // ex. redirecting link

请温柔点,我是新手。 提前感谢您的帮助!

更新:非常感谢@nate,我让它开始工作。关键的见解是,为了调用委托(delegate),必须将委托(delegate)类传递给 NSURLSession() 初始化程序,而不是使用 NSURLSession.sharedSession ()。传递 nil 作为委托(delegate)会产生习惯行为(带重定向)。这是代码的工作版本:

import Foundation
import XCPlayground

XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)

class MySession: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate {

// 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("<html>\n<head><title>Bitly</title>", options: .RegularExpressionSearch) != nil {
println("success: redirection was prevented")
} else {
println("failure: redirection went through")
}
}
}
}
}

MySession.getRedirectionInfo("http://bit.ly/filmenczer")

最佳答案

在当前的实现过程中,有两件事阻碍了您。

  1. 您永远不会在用于发出请求的 NSURLSession 实例上设置委托(delegate)属性。如果没有设置委托(delegate)属性,您的委托(delegate)方法将永远不会被调用。不要获取 NSURLSession.sharedSession(),而是查看 NSURLSession(configuration:delegate:delegateQueue:) 初始化器。第一个和最后一个参数可以分别是 NSURLSessionConfiguration.defaultSessionConfiguration()nil,有关委托(delegate)的更多信息,请参见下文。

    Note that when you use the variant of session.dataTaskWithURL that has a completion handler, delegate methods that handle response and data delivery will be ignored, but authentication and redirection handlers are still used.

  2. 您必须进行一些重构才能将 MySession 用作委托(delegate),因为您正在使用类方法来发出请求。您需要一个实例用作 session 的委托(delegate)。

我采用了一个简短且不完整的途径来让委托(delegate)使用此替代代码接收重定向——您需要像#3 中那样进行重构,以确保您仍然可以调用回调:

class func getDataFromServerWithSuccess(myURL: String, success: (response: String!) -> Void) {
let delegate = MySession()
var session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: delegate, delegateQueue: nil)
let task = session.dataTaskWithURL(NSURL(string: myURL)!) {
// ...
}
task.resume()
}

希望对您有所帮助!

关于ios - 在 Swift 中防止 URLSession 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29070420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com