Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does NSURLSession run?

I have a situation in which when the device receives a push notification, I would send a NSURLSession combined with a NSURLConnection. I have a couple of questions regarding NSURLSession.

Does NSURLSession's Data Task automatically resume in the background, if internet connection is lost?

Does NSURLSession automatically attempt to complete the task if there is no internet initially, or does the session just return with an error?

like image 268
user2856517 Avatar asked Oct 07 '13 23:10

user2856517


2 Answers

Looks like it's down to you to handle the retry.

When any task completes, the NSURLSession object calls the delegate’s URLSession:task:didCompleteWithError: method with either an error object, or nil if the task completed successfully. If the task is a resumable download task, the NSError object’s userInfo dictionary contains a value for the NSURLSessionDownloadTaskResumeData key. Your app should use reachability APIs to determine when to retry, and should then call downloadTaskWithResumeData: or downloadTaskWithResumeData:completionHandler: to create a new download task to continue that download. Go to step 3 (creating and resuming task objects).

https://developer.apple.com/library/ios/documentation/cocoa/Conceptual/URLLoadingSystem/NSURLSessionConcepts/NSURLSessionConcepts.html

like image 116
Ryan Burke Avatar answered Nov 01 '22 16:11

Ryan Burke


Does NSURLSession's Data Task automatically resume in the background, if internet connection is lost?

If the internet connection is lost you will receive an error, NSURLErrorNetworkConnectionLost (error code: -1005), in the delegate method URLSession:task:didCompleteWithError. You are responsible for retrying and/or invalidating the session using invalidateAndCancel or finishAndInvalidate (it will have already finished though in the case of a network connect loss).

Does NSURLSession automatically attempt to complete the task if there is no internet initially, or does the session just return with an error?

If there is no internet connection you will receive an error, NSURLErrorNotConnectedToInternet (error code: -1009), in the delegate method URLSession:task:didCompleteWithError. You are responsible for invalidating the session (if needed) using invalidateAndCancel or finishAndInvalidate (it will have already finished though in the case of no internet connection).

References:

URL Loading System Programming Guide

Foundation Constants Reference

like image 37
Jonathan Avatar answered Nov 01 '22 16:11

Jonathan