我正在實施「每日獎勵」方法,以便在遊戲中每天提供一些硬幣。比較iOS遊戲中每日獎勵的兩個日期
我有一個包含實際日期和時間的json。
問題是我不知道如何比較日期。
這裏是我的代碼 -
@implementation ItemRewardManager
+(NSDate *)dateFromUTCTimeStamp:(NSString *)dateString{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *myDate = [df dateFromString: dateString];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[df setTimeZone:gmt];
[[NSUserDefaults standardUserDefaults] setObject:myDate forKey:@"lastDatePlayed"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
-(void)getData
{
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:dateUrl]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
NSArray *keys = [jsonObjects allKeys];
// values in foreach loop
for (NSString *key in keys) {
NSLog(@"%@ is %@",key, [jsonObjects objectForKey:key]);
}
}
+(void)dailyReward{
NSLog(@"llega al daily");
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"HH:mm:ss zzz"];
NSDate *now = [NSDate date];
NSString *dateString = [dateFormat stringFromDate:now];
if([[[NSUserDefaults standardUserDefaults] objectForKey:@"lastDatePlayed"] isEqualToString: dateString])
{
NSLog(@"Actual date is the same as json date");
UIAlertView* alert = [[[UIAlertView alloc] initWithTitle:nil
message:@"You have win 5 coins! Come back tomorrow for more."
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles: nil] autorelease];
[alert show];
return;
}
}
@end
所以,當我打開我的應用程序,並調用這個方法,我的應用程序崩潰的一些reasone。
我認爲這個問題可能是兩個日期的比較。
有人可以告訴我,如果有什麼問題嗎?
我不認爲獎勵是客戶的工作,而是服務器之一。但是你是否已經放棄了你的「lastDatePlayed」?您將其另存爲NSDate對象並將其與NSString進行比較。可能是一個原因。順便說一句,這些結果將永遠不會相等,據我所知:) – geo
@geo你說得對。我沒有比較一些邏輯。我現在不知道每日獎勵的邏輯......你能幫助我嗎? – Vergmort
我會建議讓服務器對獎勵進行計算,只是向您發送通知,您現在可以請求它。我也會讓服務器發送* unix-timestamp *,更容易處理。也用於比較日期使用@ torip3ng的答案。並添加值到一個日期,你可以使用'NSDateComponents'和'NSCalendar'。 ('NSDateComponents * comps = [[NSCalendar currentCalendar]組件:NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit fromDate:date];')即 – geo