What happens to the current tasks present in the session when we do reset(completionHandler:) on UrlSession.
Also if it cancels the current tasks then how do we wait for the completion of the current tasks before calling reset(completionHandler:)
When you call URLSession reset, all running tasks continue to run.
A common use case to use reset is, where you want to clear all data associated to the signed-in user for example - a "sign-out" feature. Requests resumed before calling reset may use the old URL Credential store, but yet they may use the new URL cache when the response completes. This is certainly NOT what you want.
So, a more robust way to accomplish this is as follows:
prevent new tasks to be started (avoiding any data race issues)
clear all data associated to the old "session environment" - which may include access tokens and user data etc.
cancel all running tasks (asynchronously - fire & forget), then
call reset, then
enable resuming tasks.
New tasks will use the new "session environment", previously resumed tasks will complete with a cancellation error.
The first bullet point is probably the most complex one, since you need to ensure that you even do not create requests using data associated to the old session environment. That may be solved using a network layer that has a feature where incoming high level "API requests" will be queued, and that queue can be suspended and resumed.
Related
AppDelegate.applicationWillTerminate is called when the application is about to terminate. In this function, I am issuing a network request via Alamofire, to notify the server that the app is terminating. Alamofire's response handler is never invoked. It looks to me like the termination completes before the completion handler is invoked.
Alamofire's completion handlers appear to run on the main thread. I found documentation saying that the app is responsible for draining the main queue: "Although you do not need to create the main dispatch queue, you do need to make sure your application drains it appropriately. For more information on how this queue is managed, see Performing Tasks on the Main Thread." (From https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html) And this is where I am stuck.
How do I drain the main thread? I need to ensure that this last Alamofire request runs before the main thread exits.
Don't worry about “draining” the main thread. The problem is more simple than that. It's just a question of how to do something when your app is leaves the “foreground”/“active” state.
When a user leaves your app to go do something else, it is generally not terminated. It enters a “suspended” state where it remains in memory but does not execute any code. So when the app is suspended, it cannot process your request (but the app isn't yet terminated, either).
There are two approaches to solve this problem.
You could just request a little time to finish your request (see Extending Your App's Background Execution Time). By doing this, your app is not suspended, but temporarily enters a "background" state, where execution can continue for a short period of time.
The advantage of this approach is that it is fairly simple process. Just get background task id before starting the request and you tell it that the background task is done in the Alamofire completion handler.
The disadvantage of this approach is that you only have 30 seconds (previously 3 minutes) for the request to be processed. If you have a good connection, this is generally adequate. But if you don't have a good network connection in that period, the request might never get sent.
The second approach is a little more complicated: You could make your request using a background URLSession. In this scenario, you are effectively telling iOS to take over the handling of this request, and the OS will continue to do so, even if your app is suspends (or later terminated during its natural lifecycle).
But this is much more complicated than the first approach I outlined, and you lose much of the ease and elegance of Alamofire in the process. You can contort yourself to do it (see https://stackoverflow.com/a/26542755/1271826 for an example), but it is far from the obvious and intuitive interface that you're used to with Alamofire. For example, you cannot use the simple response/responseJSON completion handlers. You can only download/upload tasks (no data tasks). You have to write code to handle the OS restarting your app to tell you that the network request was sent (even if you're not doing anything meaningful with this response). Etc.
But the advantage of this more complicated approach is that it is more robust. There's no 3 minute limit to this process. The OS will still take care of sending the request on your behalf whenever connectivity is reestablished. Your app may may even be terminated by that point in time, and the OS will still send the request on your behalf.
Note, neither of these approaches can handle a "force-quit" (e.g. the user double taps on the home button and swipes up to terminate the app). It just handles the normal graceful leaving of the app to go do something else.
I noticed that in Realm Swift, there is a RealmCollectionChange
https://realm.io/docs/swift/latest/#realm-notifications
It seems to contain the objects that have changed. Can I use that notification block to add code to sync the data back to a back end database?
Is the notification block running on the main queue?
For sure you can use the provided notification mechanisms to propagate changes to a server. You should make sure though, that your requests to the server doesn't cause new changes once the server responds, otherwise you can run into a situation where you would be constantly notified about new updates, as also seen in the related docs section User-Driven Updates.
The notification block is ran on the thread on which you add it. But these APIs are only available to auto-updating Realms which require a runloop. By default only the main thread has a runloop, if you don't run any additional yourself on dedicated background threads.
Be aware that synchronizing is a non-trivial problem and using these notifications alone won't give you a full solution for every challenge involved into that problem space.
I need to pause download tasks and resume it even after app restarted. But I am unsure which method should I use, suspend or cancelByProducingResumeData.
With cancelByProducingResumeData I can get the partially downloaded data and recreate download task with it. However I have to manually manage the data, save it to file, read it back, and recreate the task and ensure the new task doesn't fail.
With suspend, I can pause and resume the download task. But can I resume this task after the app is restarted? I am using background session so tasks are preserved across restart.
cancelByProducingResumeData have requirements for it to work, does those requirements also applies to suspend/resume? Or suspend/resume is only mean for "temporarily suspends a task" as the document said?
You're overthinking the problem. The "resume data" for a download task is not the data that the task has received up to that point. It is a tiny blob of bookkeeping data—the sort of thing that you'd typically throw into an array in NSUserDefaults.
With that said, to answer the original question, a task is only valid within the context of a session. So for a foreground session, once your app quits, the session ceases to exist, so it is no longer possible to gain access to tasks in that session. Therefore, it is not possible to resume a suspended task after you relaunch the app because the task no longer exists (because its session no longer exists).
For a background session, you'd pretty much have to ask somebody on the Foundation Networking team to get an answer to that one, because it depends on the extent to which you can recreate a session after the fact. However, my guess is that it probably won't work there, either, and if it does, you should consider it unsupported.
After some research on apple developer forms, I found this
Tasks suspension is rarely used and, when it is, it's mostly used to temporarily disable callbacks as part of some sort of concurrency control system. That's because a suspended task can still be active on the wire; all that the suspend does is prevent it making progress internally, issuing callbacks, and so on.
OTOH, if you're implementing a long-term pause (for example, the user wants to pause a download), you'd be better off calling -cancelByProducingResumeData:.
So suspend may not actually stop downloading and I should use cancelByProducingResumeData: for long-term pause.
I need to save changes not only locally into Core Data, but on server too.
My concern is, in my case user can do bunch of interaction in a short time. Between interaction there is not enough time to receive success message returned from server. So either I lock the GUI, until next message returns - this is the case now -, or choose a different approach.
My new approach would be to let user do many interactions and put transactions onto undo stack provided by NSUndoManager, enabled on NSManagedObjectContext, BUT save / commit ONLY that transaction for which success message was received. How can I move undo "cursor" one at a time, commit records one by one, although context contains already planty of unsaved changes?
NSUndoManager is not really suited to this task. You can tell it to undo or redo actions, but you can't inspect those actions or selectively save data in the current undo stack.
What I've done in the past is create my own queue of outgoing changes. Whenever changes are saved locally, add those changes to a list of un-synced outgoing changes. Then use a different queue to handle processing that queue by sending them to the server and, if the server reports success, clearing out those changes. You can use NSManagedObjectContextWillSaveNotification and/or NSManagedObjectContextDidSaveNotification to monitor changes and update the outbound queue.
This means that the iOS device may have queued changes that the server doesn't know about, especially if the network is unreliable or unavailable. That's pretty much unavoidable in those situations though, unless you do something awful like refuse to let people make new changes until the network comes back up.
I have problem suspending the current task being executed, I have tried to set NSOperationQueue setSuspended=YES for pausing and setSuspended=NO for resuming the process.
According to apple docs I can not suspend already executing task.
If you want to issue a temporary halt to the execution of operations, you can suspend the corresponding operation queue using the setSuspended: method. Suspending a queue does not cause already executing operations to pause in the middle of their tasks. It simply prevents new operations from being scheduled for execution. You might suspend a queue in response to a user request to pause any ongoing work, because the expectation is that the user might eventually want to resume that work.
My app needs to suspend the time taking upload operation in case of internet unavailability and finally resume the same operation once internet is available. Is there any work around for this? or I just need to start the currently executing task from zero?
I think you need to start from zero. otherwise two problems will come there. If you resume the current uploading you cant assure that you are not missed any packets or not. At the same time if the connection available after a long period of time, server may delete the data that you uploaded previously because of the incomplete operation.
Whether or not you can resume or pause a operation queue is not your issue here...
If it worked like you imagined it could (and it doesn't) when you get back to servicing the TCP connection it may very well be in a bad state, it could have timed out, closed remotely...
you will want to find out what your server supports and use the parts of a REST (or similar) service to resume a stalled upload on a brand new fresh connection.
If you haven't yet, print out this and put it on the walls of your cube, make t-shirts for your family members to wear... maybe add it as a screensaver?