当用户每天打开应用程序超过两次时,如何启动功能? 例如,它是星期一。用户在当天打开应用程序2次,而不是触发功能。但是第二天这个过程必须重新开始。
我有这个代码用于保存app launced的数字:
var numLaunches = NSUserDefaults.standardUserDefaults().integerForKey("numLaunches") + 1
但是,如何结合当天这样做呢?
答案 0 :(得分:1)
您可以使用此课程存储有关当天以及应用程序在指定日期启动的次数的信息。
@objc class MyStats : NSObject, NSCoding {
private var date: NSDate
private(set) var launchCounter: Int
override init() {
date = NSDate()
launchCounter = 1
}
@objc func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(NSDate(), forKey: "date")
aCoder.encodeInteger(launchCounter, forKey: "launchCounter")
}
@objc required init(coder aDecoder: NSCoder) {
self.date = aDecoder.decodeObjectForKey("date") as! NSDate
self.launchCounter = aDecoder.decodeIntegerForKey("launchCounter")
}
func increaseLaunchCounter() {
launchCounter++
}
var isAboutToday: Bool {
let calendar = NSCalendar.currentCalendar()
let unitFlags = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay
let comp1 = calendar.components(unitFlags, fromDate: NSDate())
let comp2 = calendar.components(unitFlags, fromDate: self.date)
return comp1.day == comp2.day && comp1.month == comp2.month && comp1.year == comp2.year
}
func save() {
let data = NSKeyedArchiver.archivedDataWithRootObject(self)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: "stats")
}
class func loadStats() -> MyStats? {
if let
data = NSUserDefaults.standardUserDefaults().objectForKey("stats") as? NSData,
stats = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? MyStats {
return stats
}
return nil
}
}
要使用它,只需将此功能添加到AppDelegate
。
private func checkStats() {
if let stats = MyStats.loadStats() where stats.isAboutToday {
stats.increaseLaunchCounter()
stats.save()
print("The app has been launched \(stats.launchCounter) today")
// call your function...
} else {
MyStats().save()
}
}
最后在application:didFinishLaunchingWithOptions
内调用它。
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
checkStats()
return true
}