iOS Crash saying : [NSURLSessionDataTask state]: unrecognised selector sent to instance

I have screen with searchbar, when i leave this screen, i am just cancelling the ongoing running urlSessionDataTask. Here, is my code, by which i am using:

override func viewWillDisappear(_ animated: Bool) {

    if self.lastURLSessionDataTask != nil, self.lastURLSessionDataTask!.state == .running{
       self.lastURLSessionDataTask!.cancel();
       self.lastURLSessionDataTask = nil;
    }

    super.viewWillDisappear(animated);
}

As you can see in code, i am first checking if my lastURLSessionDataTask variable is not nil, then checking its state, if running then cancelling that task.

Now the issue is, it gives crash with detail as : [NSURLSessionDataTask state]: unrecognised selector sent to instance.

Also to note: It is not giving crash each and every time, this get appeared randomly at any time. I am not sure, what i am doing wrong. Can anyone have any idea? Does anyone faced this earlier?

1 answer

  • answered 2019-04-15 06:18 dreamBegin

    Because lastURLSessionDataTask is an optional type of URLSessionTask, Instead of Force Casting you should either use guard statement

    override func viewWillDisappear(_ animated: Bool) {
        guard let task = lastURLSessionDataTask, task.state == .running else { super.viewWillDisappear(animated); return }
        task.cancel()
        task = nil
    }
    

    Or Check the value by

    override func viewWillDisappear(_ animated: Bool) {
        if let task = lastURLSessionDataTask, task.state == .running {
            task.cancel()
            task = nil
        }
        super.viewWillDisappear(animated)
    }