30 Minute Post Delay Not Working With Swift - ios

How do I create my program that will only allow users to post every 30 minutes using swift? This delay time only works if the app is running, besides that it will not work or restart the time running every time the app launches. I need a way to have them wait for only 30 minutes. My code right now is:
DispatchQueue.global(qos: .background) .async {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1800)) {
UserDefaults.standard.set(false, forKey: "PostTimeLimit")
}
}
Any tips or solutions would be very helpful. Thanks!

Instead of storing whether or not the user is allowed to post, store their last post time and compare it to the current time.

Related

How to limit number of requests to a database

I have an app with a settings page where the settings of each user are stored in a MySQL database. I was wondering what is the best way to update the database for every setting the user changes while sending the minimal number of requests as I'm worried that it will crash if it sends too many( it has happened before).
I was thinking about setting a timer for ~5 seconds when the user first changes a setting, and then reset the timer to 5 seconds again if another setting is changed. Once that timer is finished it will send a request to the server to update all the settings at once. It would also constantly store the new values locally to the app, so if the user closes the app before the 5 seconds are up it will send the request once/if the app loads up again.
Is this viable/what's the best way to go about this?
You need to make some logic functions in your app, so i will try make an pseudo codes below. Hope it will give you an idea. I don`t know the MySQL details but i am trying to explain native Swift way.
First of all you should fetch data partly, I mean if you try to fetch all data at the same time your app can work very slow.. That is why we are doing pagination in the app.
As well as pagination you want to refresh the data fresh 5 seconds so i will use Timer object, which will trigger every 5 seconds the API function and catch data based on pagination. Check your below codes and implement step by step to your project. Happy Coding.
var timer: Timer?
func scheduledTimerWithTimeInterval(){
// Scheduling timer to Call the function "loadNewDataAutomatically" with the interval of 5 seconds
timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.loadNewDataAutomatically), userInfo: nil, repeats: true)
}
#objc func loadNewDataAutomatically(_ pageNumber: Int, _ pageSize: Int, onSuccess: ((Bool) -> Void)?, onError: ((Error) -> Void)?){
// Call your api here
// Send true in onSuccess in case new data exists, sending false will disable pagination
// If page number is first, reset the list
if pageNumber == 1 { self.list = [YourDataModel]() }
// else append the data to list
self.list.append(apiResponseList)
// If Api responds with error
onError?(apiError)
// Else end success with flag true if more data available
let moreDataAvailable = !apiResponseList.isEmpty
onSuccess?(moreDataAvailable)
}
Assuming that the Database (MySQL) is on a server
You can try using WorkManager for this requirement.
When the user changes their settings, save them locally (which you are already doing)
enqueue a Unique Periodic Work Request using WorkManager & set up the time at what interval should the response be sent to the server.
Minimum time interval is around 15 min. but not guaranteed at exactly 15 minutes,
the system fires it when it seems fit, also according to the Constraints that you set on your Work Request.
You can also use a OneTimeWorkRequest, if you don't need periodic, with an Initial Delay of whatever time you need.
Edit: This question was later edited and ios, swift tags were added where previously it was for android.
If anyone comes here searching for something similar for Android, this would work.

Multithreading - DispatchQueue asyncAfter delay in Swift

I am using the following code to invoke a function periodically every second. The problem is delay is actually 1.1 seconds and gets drifted more and more eventually as can be seen in NSLogs (and it is visible in other parts of the code as well apart from NSLog). Am I doing it wrong, or should I be using timer?
private func updateTimeCode() {
NSLog("Updating time")
//Some more code that doesn't take time
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
[weak self] in
self ? .updateTimeCode()
}
}
019-08-06 17:15:19.713234+0530 MyApp-Swift[8299:2685215] Updating time
2019-08-06 17:15:20.812652+0530 MyApp-Swift[8299:2685215] Updating time
2019-08-06 17:15:21.913188+0530 MyApp-Swift[8299:2685215] Updating time
2019-08-06 17:15:23.028814+0530 MyApp-Swift[8299:2685215] Updating time
It's because of the part that you say some more code not relevant taking time. They take time and time passes between each invocation of asyncAfter so basically .now() becomes something more than exactly 1 second ago.
Anyway, it's not a conventional way to achieve it. You need to use timer for that purpose. Here's a useful tutorial about how to use it. Timer in Swift

How DispatchQueue.asyncAfter behaves when application goes to background?

I would like to know how DispatchQueue.asyncAfter(deadline:execute:) behaves in case of going to background. I tried to find more information in documentation, but it's nothing there.
Let's assume case in which I invoke:
DispatchQueue.main.asyncAfter(deadline: .now() + 60.0) { ... }
What will happen if I go to background after let's say 10 seconds.
Is it going to be finished in background mode?
If not, let's assume that I will reopen the application after 2 minutes. Will it invoke the closure immediately or after remaining 50 seconds?
The most interesting part to me is to know when the timer counting down 60 seconds stops and resumes.
Update
Looking for differences between DispatchQueue.asyncAfter(deadline:execute:) and DispatchQueue.asyncAfter(wallDeadline:execute:) I've found this information from Apple Staff (source), which actually answers the question:
By the way, do you know why those two distict types are provided in Swift Dispatch library?
These model the difference between wall time (returned by gettimeofday) and Mach absolute time (returned by mach_absolute_time). The latter is independent of system clock changes but stops when you sleep. In the C API everything is flattened to Mach absolute time, which means you lose critical info. Consider what happens if you schedule a timer for 1 second in the future and then the system sleeps for 2 seconds.
To make it clear DispatchQueue.asyncAfter(deadline:execute:) uses absolute time and DispatchQueue.asyncAfter(wallDeadline:execute:) uses gettimeofday (wall time) according to this.
Here another source: What is the difference between dispatch_time and dispatch_walltime and in what situations is better to use one or the other?
Test
Based on that I prepared a test to confirm it:
override func viewDidLoad() {
super.viewDidLoad()
self.textView.text.append(
"expected times: \n1. \(Date().addingTimeInterval(60.0 * 2))\n" +
"2. \(Date().addingTimeInterval(60.0 * 3))\n" +
"3. \(Date().addingTimeInterval(60.0 * 5))\n\n")
DispatchQueue.main.asyncAfter(deadline: .now() + 60.0 * 2) {
self.textView.text.append("\n\(Date()) fired based on ABSOLUTE time (1)!")
}
DispatchQueue.main.asyncAfter(deadline: .now() + 60.0 * 3) {
self.textView.text.append("\n\(Date()) fired based on ABSOLUTE time (2)")
}
DispatchQueue.main.asyncAfter(deadline: .now() + 60.0 * 5) {
self.textView.text.append("\n\(Date()) fired based on ABSOLUTE time (3)!")
}
DispatchQueue.main.asyncAfter(wallDeadline: .now() + 60.0 * 2) {
self.textView.text.append("\n\(Date()) fired based on WALL time (1)!")
}
DispatchQueue.main.asyncAfter(wallDeadline: .now() + 60.0 * 3) {
self.textView.text.append("\n\(Date()) fired based on WALL time (2)")
}
DispatchQueue.main.asyncAfter(wallDeadline: .now() + 60.0 * 5) {
self.textView.text.append("\n\(Date()) fired based on WALL time (3)!")
}
}
Result
I run it on real device with detached debugger and locked the phone. After 3.5 minutes when I restored the application there was:
fired based on WALL time (1)!
fired based on WALL time (2)!
These two events fired exactly when I restored the application. Which proves the statement above. Events based on absolute time appeared later which confirms that their timer had stopped.
A timer started in the foreground will run in the background, if the app is already running in the background for some other reason (e.g. it is playing music and has the background mode for audio turned on, or it is performing background Core Location and has background mode for Core Location turned on).
Otherwise, it will pause in the background.
In short, when the app is suspended (when the user goes to another app), all execution stops and this timer won’t fire unless you’ve configured it for background execution. See App programming Guide for iOS: Background Execution.
As an aside, be wary of testing this from Xcode because being attached to the debugger can change the app life cycle.
It depends how your application configured the background modes. For example if you had background modes enabled and setup location monitor to always, the app can survive in background forever if user did not closed ip. So in this case the DispatchQueue.asyncAfter callback will be called.
On the other hand if background mode is disable the app will enter in freez state when is put on background, so your callback will not be called. In my tests I had notice the following flow: the dispatch queue will not stop, so if you schedule a dispatch in 60 seconds and you stay in background for 100 seconds when will come back to foreground the callback will be called immediately. If you stay in background only 30 seconds then when you will came back you will had to wait 30 more seconds.
Note you can still had background modes disabled and keep with app alive up to 3 minutes in the background if used the background task.
self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
// called when the app is about to enter in freez state
[[UIApplication sharedApplication] endBackgroundTask:weakSelf.backgroundTask];
}];

UIApplicationDidEnterBackgroundNotification remaining time for execution

In my app using iOS 9.2, Swift 2.1 I need to save some data into core data when the app goes to background. For this I registered each of the view controllers in the call path for UIApplicationDidEnterBackgroundNotification notification, with an instance method each for saving respective data.
I read on multiple places that by default the app gets about 5 seconds to finish off the execution and hence we need to use beginBackgroundTaskWithExpirationHandler to extend it to about 5 minutes. Following is an example of the selector method that responds to the above notification.
func applicationEntersBackground()
{
print("Before Extension: \(UIApplication.sharedApplication().backgroundTimeRemaining)")
let taskID = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler(nil)
print("During Extension: \(UIApplication.sharedApplication().backgroundTimeRemaining)")
saveCoreData()
if(taskID != UIBackgroundTaskInvalid)
{
UIApplication.sharedApplication().endBackgroundTask(taskID)
}
print("After Extension: \(UIApplication.sharedApplication().backgroundTimeRemaining)")
}
Following is the results of print() statements
Before Extension: 179.933103708318
During Extension: 179.930266333336
After Extension: 179.922843541659
My doubts are
Why is the remaining time about 180 seconds even before I requested for time extension? I tried multiple times. It is always close to 180 seconds and not the 5 seconds as suggested.
Why doesn't the call to beginBackgroundTaskWithExpirationHandler have any impact on the remaining time?
Once the applicationEntersBackground method of a VC returns, similar notification is sent to another VC's corresponding method. Suppose 180 seconds is the total extended duration and VC1 spends about 10 seconds on notification handling, does VC2 notification handler get around 170 seconds between its beginBackgroundTaskWithExpirationHandler - endBackgroundTask calls?
Between successive invocations of the notification handlers of different VCs, there is obviously a very short period where the extension request is not active. How does the timing play out in this case? Does the 5 second counter (provided it is true) come back to life as soon as an endBackgroundTask call is made, and possibly terminate the application before the next VC can get its notification?
Appreciate any help.
By looking at the documentation for backgroundTimeRemaining:
While the app is running in the foreground, the value in this property remains suitably large. If the app starts one or more long-running tasks using the beginBackgroundTaskWithExpirationHandler: method and then transitions to the background, the value of this property is adjusted to reflect the amount of time the app has left to run.
To answer your questions:
backgroundTimeRemaining stays around 180 while the application is in foreground so you can tell what time you'd have once you start a background task. This value is not an indicator of how long are you allowed to run without a background task.
beginBackgroundTaskWithExpirationHandler has an impact, as you can see, the remaining time decreased (by a small value as the method doesn't take much time)
What matters here is the time passed between the call to beginBackgroundTaskWithExpirationHandler and the one to endBackgroundTask. You can split whatever you need the time interval between your calls, providing you don't exceed the 180s limit
Once you call endBackgroundTask the application will be suspended, regardless it took 2 seconds or 179 seconds.
You can find out more details about application entering background here. I'd recommend going through the documentation, it might clarify other questions you might have on this matter.

Execute a line of code after a certain amount of time in the background on iOS 7

To provide some context, the application I'm working on allows the user to record a series of events along a timeline. One important piece of feedback we received from beta testers was that when the user exits the app while recording they'd like the timer to keep up to date for a set amount of time.
For example if the user has recorded 5 minutes and then leaves the app to check an email for 20 seconds, the timer should be 5:20, but it was actually still 5 minutes.
So we've fixed that - the app now would now show 5:20, and this works in the background.
However we can't figure out a way to stop it after a certain amount of time. A user might want the timer to resume if the app is in the background for a short amount of time, but if you leave it in the background for 30 minutes, the timer will update, and I'd like to be able to give the users an optional cut-off time so that the app pauses after a set amount of time.
I've tried listening out for UIApplicationDelegate notifications, but the problem is I'm looking for a point between applicationDidEnterBackground: and applicationWillTerminate, but there's sadly nothing to cater for my needs there.
To summarise, I'd like to have a grace period of 30-60 seconds from applicationWillResignActive: to determine whether or not to pause the timer, or let it keep going.
Would this be possible?
Thanks in advance
It's generally a bad idea to assume your app will be running in the background.
A better way to think about it IMO would be to set a variable to the current time in applicationDidEnterBackground: and check the time interval to now in applicationWillBecomeActive: :
If the interval is bigger that your grace period, have the time backup to when the app was paused.
If it is smaller, update it as if the app was never in the background.
Use dispatch_after to execute a block of code after a certain number of second:
int64_t delay = 30.0; // In seconds
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, delay * NSEC_PER_SEC);
dispatch_after(time, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0ull), ^(void){
//DO SOMETHING
});
Swift 3.0 Xcode 8.0 Code sample:
Using delegate methods : applicationWillBecomeActive & applicationWillResignActive to capture the time in between.
OR
let deadlineTime = DispatchTime.now() + .seconds(30)
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
alert.dismiss(animated: true, completion: nil)
}
Hope this helps.

Resources