【发布时间】: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