我在“主页”视图控制器中更新当前日期标签时出现问题,如下所示:
func settingTodayLabel() {
let todayFormatter = NSDateFormatter()
todayFormatter.dateFormat = "d MMM YYYY"
todayLabel.text = todayFormatter.stringFromDate(NSDate())
}
当'ApplicationDidBecomeActive'调用此函数时,我希望在第二天从背景调用app但今天没有更改时更新今天的标签文本。显示旧日期。但是,如果我在设置中手动修改日期,则可以正常工作..
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "settingTodayLabel", name: UIApplicationDidBecomeActiveNotification, object: nil)
}
答案 0 :(得分:1)
UIApplicationDidBecomeActiveNotification
,因此您需要在0:00每天触发另一个通知以更新标签。
创建一个本地推送通知,该通知在0:00触发并让它广播您收听的自定义NSNotification,如
NSNotificationCenter.defaultCenter().addObserver(self, selector: "settingTodayLabel", name: "DateChangedNewDay", object: nil)
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let notificationType = UIUserNotificationType.None
let settings = UIUserNotificationSettings(forTypes: notificationType, categories: nil)
application.registerUserNotificationSettings(settings)
var localNotification:UILocalNotification = UILocalNotification()
localNotification.fireDate = NSCalendar.currentCalendar().startOfDayForDate(NSDate())
localNotification.repeatInterval = NSCalendarUnit.CalendarUnitDay // for testing: .CalendarUnitMinute
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
return true
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
NSNotificationCenter.defaultCenter().postNotificationName("DateChangedNewDay", object: nil)
}
}
视图控制器
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var todayLabel: UILabel!
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "settingTodayLabel", name: UIApplicationDidBecomeActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "settingTodayLabel", name: "DateChangedNewDay", object: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.settingTodayLabel()
}
func settingTodayLabel() {
let todayFormatter = NSDateFormatter()
todayFormatter.dateFormat = "d MMM yyyy" // for testing: "d MMM yyyy HH:mm"
todayLabel.text = todayFormatter.stringFromDate(NSDate())
}
}
我在网上放了一个示例应用程序,每分钟更新一次:https://github.com/vikingosegundo/LabelUpdatingEachMinute
"d MMM YYYY"
最有可能是"d MM yyyy"
,因为Y
代表年份#34;一年中的一周" 年份没有&#39} ; t从1月1日开始,但仅在几周之间切换:1月的前3天可以属于12月到下一年的最后3天的最后一年。 y
代表我们所知的年份:从1月1日开始。