允许用户每天只访问一次UIButton(考虑时区)

时间:2016-03-07 10:57:45

标签: ios iphone

我想让用户只在一天内在UIButton的操作中执行一些代码。如何实施?我发现NSTimer不适合这个目的。

3 个答案:

答案 0 :(得分:0)

您可以像这样使用NSUserDefaults

-(void)btnPressed:(id)sender{
    NSDateFormatter *df = [NSDateFormatter new];

    df.dateFormat = @"d/m/yyyy";

    NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];


    if ([pref boolForKey:[df stringFromDate:[NSDate date]]]) {
        // do nothing button is used
    }else{
        [pref setBool:YES forKey:[df stringFromDate:[NSDate date]]];

        // do the daily operartion for one time
    }
}

答案 1 :(得分:0)

使用NSTimer是个坏主意,因为如果您的应用被用户杀死,它将在重启时没有相同的计时器。您可能希望保存上次访问的日期,而不是将日期与上次访问日期进行比较,类似于:

夫特

//store lastAccessDate somewhere in your system NSUserDefaults for example
var lastAccessDate:NSDate!

//on button click or other action get today's date and compare to lastAccessDate
let newAccessDate = NSDate()
if (newAccessDate.timeIntervalSinceDate(lastAccessDate)/1000.0 > 24*60*60) {
    //do something here
    lastAccessDate = newAccessDate
}

目标-C

//store lastAccessDate somewhere in your system NSUserDefaults for example
NSDate *lastAccessDate;

//on button click or other action get today's date and compare to lastAccessDate
NSDate *newAccessDate = [NSDate date];
if ([newAccessDate timeIntervalSinceDate:lastAccessDate]/1000.0 > 24*60*60) {
    //do something here
    lastAccessDate = newAccessDate;
}

答案 2 :(得分:0)

NSDate *lastAccessDate;

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-dd-MM HH:mm:ss a"];

lastAccessDate = [dateFormatter dateFromString:[arrList valueForKey:@"LastUpdatedDate"]];

//    //on button click or other action get today's date and compare to lastAccessDate
NSDate *newAccessDate = [dateFormatter dateFromString:[arrList valueForKey:@"CurrentTime"]];

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *componentsForFirstDate = [calendar components:NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear fromDate:lastAccessDate];

NSDateComponents *componentsForSecondDate = [calendar components:NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear fromDate:newAccessDate];

if ([componentsForFirstDate day] != [componentsForSecondDate day])