如何在iOS中的特定時間運行功能?

[英]How to run a function at a specific time in iOS?


I want to run a function in my app at a specific time. At 5pm I'd like my app to display a simple alertView telling the user it's 5pm.

我想在特定時間在我的應用中運行一個功能。下午5點,我希望我的應用程序顯示一個簡單的alertView告訴用戶下午5點。

It's safe to assume the app is active and open at that time. I'm aware how to run a function after a delay (but that is dependant on when the method is first called).

假設應用程序處於活動狀態並且在那時打開是安全的。我知道如何在延遲后運行一個函數(但這取決於首次調用該方法的時間)。

One approach is possibly sending a local notification. Is that the best approach? I was hoping to avoid using that as it depends on the user granting permissions to send notifications.

一種方法可能是發送本地通知。這是最好的方法嗎?我希望避免使用它,因為它取決於用戶授予發送通知的權限。

1 个解决方案

#1


1  

If "it's safe to assume the app is active and open at that time" — though I don't see how it could possibly be safe to assume that — then a timer (NSTimer) is most appropriate. Simply use the difference between what time it is now and the time you want the function called to tell the timer when to fire.

如果“可以安全地假設應用程序處於活動狀態並且當時打開” - 盡管我沒有看到它可能是安全的假設 - 那么計時器(NSTimer)是最合適的。只需使用現在的時間與您希望調用的函數告訴計時器何時觸發的時間之間的差異。

Local notifications are to notify the user about something, when your app is not frontmost. In other words, they are a way of telling the system to provide some notifying interface on your behalf. Notification can appear in the notification center, on the lock screen, as a banner or alert, and as a sound. If that isn't what you want, don't use a local notification.

當您的應用不在最前面時,本地通知會通知用戶某事。換句話說,它們是告訴系統代表您提供一些通知界面的一種方式。通知可以顯示在通知中心,鎖定屏幕上,作為橫幅或警報,以及聲音。如果這不是您想要的,請不要使用本地通知。

It's true that if your app happens to be frontmost when a local notification fires, then the local notification notifies your app rather than showing the user a banner / alert. If that's acceptable, then this would be a reasonable use of a local notification. But don't use a local notification as a substitute for doing your own timing arithmetic! Use it because you want to notify the user.

確實,如果您的應用在本地通知觸發時恰好位於最前端,則本地通知會通知您的應用,而不是向用戶顯示橫幅/警報。如果這是可以接受的,那么這將合理地使用本地通知。但是,不要使用本地通知代替自己的計時算術!使用它是因為您想要通知用戶。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/10/23/72578c2f2ff95d591a4f10fd04fd3034.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com