NSURLSessionDataTask dataTaskWithURL completion handler not getting called

后端 未结 2 558
梦毁少年i
梦毁少年i 2020-12-03 15:00

I have been learning Objective C lately, and I decided to try connections.

Everything was great with NSURLConnection, until I discovered it was outdated, and tried t

相关标签:
2条回答
  • 2020-12-03 15:58

    Check the location of your code.

    Although it is not stated in OP where the code was located, I found, after much looking and many iterations, that putting sample code in -viewDidLoad never executed the completion handler. Moving the code into

    - (void)viewWillAppear:(BOOL)animated { }
    

    solved the never completing task issue. (I still don't understand why though.)

    0 讨论(0)
  • 2020-12-03 16:02

    If you're going to use the completion block rendition of the data task, rather than specifying a delegate of nil, like this:

    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject
                                                                 delegate: nil
                                                            delegateQueue: [NSOperationQueue mainQueue]];
    

    You should instead instantiate your session using the method that does not take a delegate at all:

    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject];
    

    Or, alternatively, given that you're not customizing your configuration at all, you can skip the instantiation of the NSURLSessionConfiguration altogether and use the shared NSURLSession:

    NSURLSession *defaultSession = [NSURLSession sharedSession];
    

    But, bottom line, you should not use the sessionWithConfiguration:delegate:queue: rendition unless you're going to implement the delegates, in which case you wouldn't use the rendition of the NSURLSessionDataTask method with the completionHandler parameter.

    Also, make sure your device/simulator is running iOS 7.0 or greater.

    0 讨论(0)
提交回复
热议问题