Search code examples
iosswiftios9nsurlsessiondatatask

How to point to a task with it's own completions closure ? ios swift


I am sending request using tasks, in this way :

    let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in

                dispatch_async(dispatch_get_main_queue(), {

                    //remove from queue
                    weakself?.popTask(task: task)
    }
}

self.pushTask(task)
task.resume()

i need to push the task into a queue before resume. then i need to pop it after it's finished. the problem that i got this error : variable used within it's own initial values

what should i do? is it possible to create a task, then to set it's completion handler ?

Thanks


Solution

  • I think you're correct that the completion block can't refer to task because it hasn't been created yet.

    That is what is meant by:

    variable used within it's own initial values

    To get around this, simply declare the constant before you set it. e.g.

    let task: NSURLSession
    task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
    
                dispatch_async(dispatch_get_main_queue(), {
    
                    //remove from queue
                    weakself?.popTask(task: task)
    }