NSURLSession dataTaskWithRequest 未被调用 [英] NSURLSession dataTaskWithRequest not being called

查看:66
本文介绍了NSURLSession dataTaskWithRequest 未被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有第二个 NSURLSession 直接从前一个的 completionHandler 调用(它依赖于从第一次调用生成的 cookie).它工作了一段时间,有时仍然有效,但大部分时间没有.当我通过调试器设置时,它只是从 dataTaskWithRequest 行到 task.resume() 调用之后的行.有什么想法吗?

I have a second NSURLSession that is being called directly from the completionHandler of the previous one (it is dependent on the cookies generated from the first call). It worked for a while and sometimes still works, but most of the time does not. When I set through the debugger, it simply goes from the dataTaskWithRequest line to the line past the task.resume() call. Any thoughts?

func getDates () -> [NSDate] {
    var urlDays = NSURL(string: "https://mycorrecturl.com")
    var requestDays = NSMutableURLRequest(URL: urlDays!)
    let sessionDays = NSURLSession.sharedSession()

    // Create array of NSDate objects
    var allDates = [NSDate]()

    var task = sessionDays.dataTaskWithRequest(requestDays, completionHandler: {data, response, error -> Void in

        // Convert into array of NSDate objects

    })
    task.resume()
    return allDates
}

为什么这个 dataTaskWithRequest 函数不会触发?

Why would this this dataTaskWithRequest function just not fire?

推荐答案

您面临的问题是 dataTaskWithRequest 是一个异步调用,这就是您收到空数组的原因(这是唯一完成并返回一个同时,有时您会收到数据).

The problem that you are facing is that dataTaskWithRequest is an asynchronous call, that's the reason why you receive an empty array (that's only chance that finish and return a the same time and sometimes you receive data).

为此,您需要使用从 dataTaskWithRequests 的闭包中获取调用的闭包.

For that, you need to use a closure that get's call from the closure of dataTaskWithRequests.

像这样(这里我只展示了带闭包的声明方法):

Like this (here I only show you the declaration method with a closure):

func getDates (success:([NSDate])->Void){

在您的网络调用正文中:

And in the body of your network call:

var task = sessionDays.dataTaskWithRequest(requestDays, completionHandler: {data, response, error -> Void in

    // Convert into array of NSDate objects
    var yourArrayOfNSDateConverted:[NSDate] = [NSDate]()
    success(yourArrayOfNSDateConverted)
})

显然 yourArrayOfNSDateConverted 包含您的处理数据,并且您还需要管理错误(为此您可以添加另一个闭包).

Obviously the yourArrayOfNSDateConverted contains your process the data and also you need to manage the error (for that you can add another closure).

这篇关于NSURLSession dataTaskWithRequest 未被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆