Get Firebase remote configuration synchronously - ios

I use Firebase for A/B testing. I noticed that i cannot get remote configuration synchronously, because
-(void)fetchWithCompletionHandler:(nullable FIRRemoteConfigFetchCompletion)completionHandler;
method of FIRRemoteConfig executes completion block on main thread. So i have no way to block main thread until it done.
P.S. I try to get remote configurations in didFinishLaunchingWithOptions of AppDelegate

Like most modern web APIs Firebase Remote Config fetches data from its servers asynchronously and has no option to read synchronously. There is no way to say how long the fetch may take, so it's a bad idea to block the main thread. Completion handlers are honestly the best way to deal with data that is loaded asynchronously, and that must be available before the user can continue using the app.
A few related questions:
Swift: Wait for Firebase to load before return a function
How to make app wait until Firebase request is finished
How do I wait for an asynchronously dispatched block to finish?
Force asynchrounous Firebase query to execute synchronously?
In general: making the user wait for updated configuration data, leads to a lesser user experience. For most apps you can just as easily start fetching updated remote config data when you start them, but instead of waiting the app immediately continue with the data it loaded last time. When the user restarts the app, it applies the previously loaded data, which then happens without any delay.

Related

Synchronous API requests with Queue in Swift?

I need to execute synchronous requests on API using Swift. Requests must be queued. Meaning, if one is already in progress and it awaits response it must not be canceled or interrupted by the next synchronous request that enters queue or is already in queue.
Requests must be executed in order as they enter queue (FIFO). Next request must not start until previous is finished/completed in the queue.
Also, every single request in queue must be executed until queue is empty. Synchronous requests can enter queue at any time.
I meant to implement a Synchronous API Client as a singleton which contains its own Queue for queued requests. Requests must not stop/freeze UI. UI has to be responsive on user interaction all the time.
I know it can be done with semaphores but, unless you know what your are doing and you are completely sure how semaphores work, it is not the safest or maybe the best way do it. Otherwise, potential bugs and crashes could appear.
I'm expecting successful execution of every synchronous request that enters queue (by FIFO order, regardless if it returns success or an error as a response) and UI updates immediately after.
So, my question is what is the best way to approach and solve this problem?
Thanks for your help and time.
You can create your own DispatchQueue and put you operations on it as DispatchWorkItems. It is serial per default. Just remember to call your completions on DispatchQueue.main if you plan to update the UI.
John Sundell has a wonderful article about DispatchQueues here:
https://www.swiftbysundell.com/articles/a-deep-dive-into-grand-central-dispatch-in-swift/

Handling of Alamofire requests as iOS app is terminating

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.

Chaining Background Tasks Alamofire

I have a question about Alamofire and its behavior with a SessionManager configured for background Tasks. I am using it to upload a video in the background.
Step I: Uploading Video:
This part is standard, however, when the upload completes:
Step II: Completing Upload:
I need to send a DELETE request to the server letting it know that the video upload is complete. If successful, the response will contain a location header for the newly uploaded video.
Step III Add Video MetaData:
With this location I need to PATCH request the video metadata: Title and Description.
So my question is about overriding the Session Manager delegate closures. I can override sessionDidFinishEventsForBackgroundURLSession and taskDidComplete and when I am completely finished with the background I need to call the system completionHandler that I am storing as a property on the SessionManager... So when/ where should I fire off the DELETE request and then when/where should I fire off the PATCH request?
Should I create 3 different background session configuration identifiers so I can identify them and make sure I chain them in right order? Because obviously I cannot say in the closure: the first time you are called fire off this request, but the second fire off this one? And which closure of the 2 is the right one to finish off the whole process and call the system completionHandler? I'm not sure if this is right because I will be out of sync with the Alamofire upload response handler.
Also I am wondering about the Alamofire response handlers. If the app was in the foreground the whole time? I would simply chain the alamofire requests together using the response handlers? but if the app terminated and is running in the background will these handlers still be around?
Any insight here would be greatly appreciated. I realize there is a lot going on here and Apple eve rate limits background tasks, I'm just wondering if this is possible and if so how to go about it?
Should I create 3 different background session configuration
identifiers so I can identify them and make sure I chain them in right
order?
I dont think you will need multiple background sessions just to identify for which request the completion block was called and to chain the next request. You can achieve it with
Asynchronous NSOperation :
You can make use of Asynchronous NSOperations to chain the multiple requests. Add the dependency among the operations and let the iOS handle scheduling and handling the dependencies. Please note : I mentioned Asynchronous NSOperation. NSOperations are Synchronous by nature.
Promise kit :
If Asynchronous NSOperations are way too complicated, you can always use Promise kit. Promise kit will take care of executing the request only after the specific request completes and the whole dependency chain will short circuit if one on the top fails.
Simply create a new data task in the completion block of upload task to upload the video. Rather than using the delegate pattern for tasks use completion blocks. That way you dont have to identify for which request the delegate was called, as each task will have its own completion block, you can easily chain them up while writing the code.
if the app terminated and is running in the background will these
handlers still be around?
Am not 100% sure though, but as far as I know, when you schedule the background task (background session), task will continue to execute even if the app is killed.After all, thats why we use background session. So I believe the completion handlers will be executed even if you kill the app.

Can RealmCollectionChange be used as a way of syncing data back to server?

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.

Importing And saving large data into coredata blocks every thing and application quits

I am developing an application in which huge amount of data has to fetched from web server and then this data has to be stored in core data.
I am using private Contexts for that like:
[privateContext performBlockAndWait:^{ //Code }];
Firstly I was calling this block from background thread by using dispatch queues. But the core data was not functioning well. Then I read the documentation and found out that this block has to be called from the main thread. And after that everything worked fine.
But now the problem is that during data storing if I press the home button and come back again to application the UI of application hangs and after sometime the application crashes with no crash log. And I cannot figure out what the problem is.
Another thing if I call this block from background thread this problem does not happen, but then the other issues starts arriving.
Can you post the complete code that is performing the block?
Are you receiving any memory warnings during the execution of the app?
Are you storing and fetching in small batches or are you fetching all your data and storing it at once?
My educated guess is the following:
performBlockAndWait is blocking the main thread. When you suspend the app and resume it again, the main thread will continue to be blocked (therefore the UI will not be updated as the main thread is in charge of UI updates). If you have large amounts of data in memory for storage AND your app is blocking the main thread, your app is being terminated due to memory usage or non responsiveness.
I don't understand why do you have problems doing this operation in a background thread, I've used it multiple times and everything worked like a charm. I've used NSOperationQueue with block and in the applicationWillResignActive I create a background task to ensure that the operation is finished up before suspending the app.
If you can provide more info.
Thanks!

Resources