NSURLSessionTaskDelegate method URLSession: task: didCompleteWithError: never called

All of my network code relies on NSURLSession delegate methods, not termination handlers. My data and download tasks work fine, but my download tasks never result in URLSession:task:didCompleteWithError:. However URLSession:dataTask:didReceiveData:, the URLSession:dataTask:willCacheResponse:completionHandler:delegate methods are also ARE .

If I set the resource timeout to a really low value for my session object, it didCompleteWithErrorsis called, but this is clearly not a solution.

Any ideas? I'm going to go crazy.

Thank.

+4
source share
4 answers

didCompleteWithError, willCacheResponse, completionHandler. completionHandler.

NSURLSession, completionHandler (, , ..). , , completionHandler.

+5

. - - ​​ - , NSURLSessionTaskDelegate . .

NSURLSession ; completionHandler .

:

func dataTaskWithRequest(_ request: NSURLRequest) -> NSURLSessionDataTask

func dataTaskWithRequest(_ request: NSURLRequest, completionHandler completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask

completionHandler, - NSURLSessionTaskDelegate . , NSURLSession.

. task, :

import UIKit
import XCPlayground

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true


class MyDelegate:NSObject, NSURLSessionTaskDelegate
{
    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
        NSLog("Delegate called")
    }
}


let myDel = MyDelegate()
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config, delegate: myDel, delegateQueue: NSOperationQueue())
let url = NSURL(string: "http://httpbin.org")
let request: NSURLRequest = NSURLRequest(URL: url!)

// With completionHandler, delegate method above NOT called
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
        NSLog("Task done")
})

// Without completionHandler, delegate method above IS called
//let task : NSURLSessionDataTask = session.dataTaskWithRequest(request)

task.resume()

TL;DR: , , NSURLSession ? ; , Handler.

+2

, NSURLSession , .

API, API NSURLSession . , , :

  • , , .

  • .

:

NSURLSession Handler

0

completionHandler willCacheResponse, .

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask willCacheResponse:(NSCachedURLResponse *)proposedResponse completionHandler:(void (^)(NSCachedURLResponse *__nullable cachedResponse))completionHandler {

    NSLog(@"%s", __FUNCTION__);
    completionHandler(proposedResponse);
}
0

All Articles