2016-03-07 108 views
-3

我想允許用戶在UIButton的動作中只執行一次內部的一些代碼。它如何實施?我發現NSTimer不適合這個用途。允許用戶每天只訪問一次UIButton(考慮時區)

+3

儲存最後使用日期。檢查它是否是前一天。相應地允許/禁止,您可以使用NSTimer再次檢查每個分鐘,或編程允許值。 – Larme

+1

@Larme但是使用設備日期不安全,因爲用戶可以通過設置更改設備日期。 –

+0

你不能相信用戶數據。期。我認爲這是保護您的資源的錯誤方法 - 但如果仍然存在,您可能需要聯繫Web服務獲取有效的時間戳,並在離線情況下使該功能無用。不要忘記 - 你存儲在你的設備上的東西可能會被玷污。 – Eiko

回答

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 
    } 
} 
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 
} 

Objective-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; 
} 
+0

使用Objective c,但是NSTimer在這裏沒有用處。 –

+0

你沒有在你的問題或標籤中提及編程語言。在Objective-C代碼看起來非常相似,我已經更新了我對這兩種語言的答案。 – NSDmitry

+0

這條線是幹什麼的「if([newAccessDate timeIntervalSinceDate:lastAccessDate] /1000.0> 7 * 24 * 60 * 60)」 –

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]) 
相關問題