我在 Xcode 6.2(测试版)中使用 Swift,但在 6.1 发行版中遇到了同样的问题。我正在尝试使用 NSURLSession 并相信我已经正确设置了它(请参阅下面的代码)。问题是我有一个委托(delegate)设置来处理通过代码发生的重定向。我实际上需要在最终重定向之前捕获 cookie,我正在通过委托(delegate)执行此操作:
func URLSession(_:NSURLSession, task:NSURLSessionTask, willPerformHTTPRedirection:NSHTTPURLResponse, newRequest:NSURLRequest, completionHandler:(NSURLRequest!) -> Void )
这有效,我能够成功执行代码并捕获我需要的 cookie。问题是我需要在函数末尾添加 task.cancel()
否则它似乎永远不会完成并返回到委托(delegate)人(父?)函数。因此,我丢失了重定向 URL 的结果(尽管在我当前的项目中它是无关紧要的)。奇怪的是,这工作了一段时间,似乎停止了。我不相信我输入了任何更改它的代码,但必须发生一些事情。下面是相关代码。
NSURLSession 函数:
func callURL (a: String, b: String) -> Void {
// Define the URL
var url = NSURL(string: "https://mycorrecturl.com");
// Define the request object (via string)
var request = NSMutableURLRequest(URL: url!)
// Use default configuration
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
// Create the NSURLSession object with default configuration, and self as a delegate (so calls delegate method)
let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
// Change from default GET to POST (needed to call URL properly)
request.HTTPMethod = "POST"
// Construct my parameters to send in with the URL
var params = ["a":a, "b":b] as Dictionary<String, String>
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
// Do some other stuff after delegate has returned...
})
task.resume()
return
}
委托(delegate)代码:
func URLSession(_:NSURLSession, task:NSURLSessionTask, willPerformHTTPRedirection:NSHTTPURLResponse, newRequest:NSURLRequest, completionHandler:(NSURLRequest!) -> Void ) {
// Check Cookies
let url = NSURL(string: "https://mycorrecturl.com")
var all = NSHTTPCookie.cookiesWithResponseHeaderFields(willPerformHTTPRedirection.allHeaderFields, forURL: url!)
// Get the correct cookie
for cookie:NSHTTPCookie in all as [NSHTTPCookie] {
if cookie.name as String == "important_cookie" {
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(cookie)
}
}
task.cancel()
}
它过去常常不调用 task.cancel() 就返回到调用函数。如果未调用 task.cancel(),代码是否有任何看起来不对的地方会导致它只是卡在委托(delegate)函数中?
编辑:我要添加什么代码来解决这个问题。
最佳答案
如果您不取消请求,您的willPerformHTTPRedirection
应该调用completionHandler
。正如文档所说,这个 completionHandler
参数是:
A block that your handler should call with either the value of the request parameter, a modified URL request object, or
NULL
to refuse the redirect and return the body of the redirect response.
关于ios - 无法在不终止任务的情况下从 NSURLSession 委托(delegate)返回调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27050053/