Chetan sharma
Chetan sharma

Reputation: 388

How to stop task or section from NSURLSession

I am Using NSURLSession for call an post API, but when i turn of the wifi and then hit the web service and again turn on the wifi NSURLSession is calling that previously call web service, i want to stop this process. i read on some of documents that NSURLSession store the section of every service call when connection break in any situation , and again hit that service when connection established again. So now i am not getting any solution to stop that service call after connection reconnect to my device. Any one please help me. Thanks in advance.

Below is my code i used.

            let token: NSString!

            let urlPath: NSURL!

            if provider .isEqualToString("No"){
                urlPath  = NSURL(string: kAPI_SERVERBASEURL + (url as String))
            }
            else{
                urlPath  = NSURL(string: kAPI_SERVERBASEURLSEARCHPROVIDER + (url as String))
            }

            var postJsonData = NSData()
            var jsonString   = NSString()

            do {
                postJsonData = try NSJSONSerialization.dataWithJSONObject(dictRequest, options:[])
                jsonString = NSString(data: postJsonData, encoding: NSUTF8StringEncoding)!
                NSLog("request - %@", jsonString);

                // do other stuff on success

            } catch {
                print("JSON serialization failed:  \(error)")
            }

            let request = NSMutableURLRequest(URL: urlPath);
            request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
            request.HTTPShouldHandleCookies = false
            request.timeoutInterval = 120 ;
            request.HTTPMethod = "POST";

            if NSUserDefaults.standardUserDefaults().valueForKey(kAccessToken) != nil{

                token = NSUserDefaults.standardUserDefaults().valueForKey(kAccessToken) as! NSString
                //token = "tk_1vNoEoZRxJwY"
                request.setValue("\(token)", forHTTPHeaderField: "access_token")
            }

            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.HTTPBody = postJsonData
            let session = NSURLSession.sharedSession()
            let task = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

`

Upvotes: 1

Views: 4028

Answers (1)

Vishnuvardhan
Vishnuvardhan

Reputation: 5107

It may help you.

1.Declare one variable about the NSURLSessionTask like

var task: NSURLSessionTask? = nil

2.When ever you need to call dataTaskWithRequest assign the object to declared object like

task = NSURLSession.sharedSession().dataTaskWithURL(NSURL(fileURLWithPath: ""))

3.when you want to cancel the request just do the below.

if nil != task {
    task!.cancel()
    task = nil
}

Suppose you want cancel the request before calling another one combine both 2 and 3 steps like

if nil != task {
    task!.cancel()
    task = nil
}
task = NSURLSession.sharedSession().dataTaskWithURL(NSURL(fileURLWithPath: ""))

Upvotes: 3

Related Questions