Gamecenter Score Not Submitting Correct Score - ios

When I test my game the score of my game ends in a time of 3.49 seconds, but in gamecenter the score that shows up in the leaderboards is 1:01:52.76. I think the problem is that i get a yellow flag that says incompatible integer to integer conversion assigning to int_64 (aka long long) from NSString. Here is the part of the code that shows the error.
- (IBAction)buttonPressed:(id)sender {
[self startTimer];
count--;
countLabel.text = [NSString stringWithFormat:#"Score\n%i", count];
// 2
if (count == 0) {
[self.stopWatchTimer invalidate];
timeLabel.hidden = YES;
// Create date from the elapsed time
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:self.startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
// Create a date formatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"'Your time: 'ss.SSS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
// Format the elapsed time and set it to the label
NSString *timeString = [dateFormatter stringFromDate:timerDate];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Time is up!"
message: timeString
delegate:self
cancelButtonTitle:#"Play Again"
otherButtonTitles:#"Level Select",nil];
[alert show];
if (count == 0) {
GKScore *scoreReporter = [[GKScore alloc] initWithLeaderboardIdentifier:#"tap_novice"];
scoreReporter.value = timeString;
scoreReporter.context = 0;
NSArray *scores = #[scoreReporter];
[GKScore reportScores:#[scoreReporter] withCompletionHandler:^(NSError *error) {
if (error == nil) {
NSLog(#"Score reported successfully!");
} else {
NSLog(#"Unable to report score!");
}
}];
}
}
}
#end

Instead of the current line you have:
scoreReporter.value = timeString;
You should use:
int64_t timeAsInt = [timeString longLongValue];
scoreReporter.value = timeAsInt;
See the following link

Related

Loading bulk event in ios calendar get error

I am trying to do a massive load of events on a ios calendar either local or in gmail (the calendar chooses the user as I describe in the following answer) using objective-c.
Adding an event with the functions I've put below works fine for me, but when I have to do a massive load of eg 527 events (since I'm trying to add a student's school calendar) it does not work correctly.
When doing the bulk load I inserted well about 100 events or so and then it starts to crash and crash the app.
The errors that it gives me are the following:
2016-11-17 17:23:35.966 [230:11481] Calendar was not set: 1 Error
Domain=EKErrorDomain Code=1 "No calendar selected."
UserInfo={NSLocalizedDescription=No calendar selected.}
2016-11-17 17:23:49.545 [230:12644] Connectioninterrupted!
2016-11-17 17:23:49.568[230:12587] Error getting changed object IDs
since timestamp 501092601.149441 from daemon: Error
Domain=NSMachErrorDomain Code=4097 "unknown error code"
My question is this: Is there any error in my massive loading approach or in the functions I have done? or else Is there any other better way to do a massive load of events?
Function that inserts the list of events:
- (int) addCalendarEvents: (EKCalendar *) cal {
int num = 0;
for (int i=0; i < [calendario.eventos count]; i++) {
NSDictionary * nextDict = [calendario.eventos objectAtIndex:i];
Evento_DTO * evento_dto = [[Evento_DTO alloc] initWithEventos:nextDict];
BOOL res = [self addEventCalendar: evento_dto calendar: cal];
if(res){
num++;
}
}
return num;
}
And the function that adds the event to the calendar is as follows:
-(BOOL)addEventCalendar: (Evento_DTO *) evento calendar: (EKCalendar *) cal{
__block BOOL res = NO;
if (!SYSTEM_VERSION_LESS_THAN(#"6.0")) {
// iOS 6 and later
EKEventStore *eventStore = [[EKEventStore alloc] init];
//We get the dates of the event
Fecha_DTO *fechaStart = [[Fecha_DTO alloc] initWithFecha:(NSDictionary *)evento.dtStart];
Fecha_DTO *fechaEnd = [[Fecha_DTO alloc] initWithFecha:(NSDictionary *)evento.dtEnd];
// Format the dates to type NSDate
// Start Date
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyyMMdd'T'HHmmss"];
if (fechaStart.tzid == nil) {
[df setTimeZone: [NSTimeZone systemTimeZone]];
}else{
[df setTimeZone:[NSTimeZone timeZoneWithName:fechaStart.tzid]];
}
NSDate* parsedDateS = [df dateFromString: fechaStart.fecha];
// End Date
NSDateFormatter* df2 = [[NSDateFormatter alloc] init];
[df2 setDateFormat:#"yyyyMMdd'T'HHmmss"];
if (fechaEnd.tzid == nil) {
[df2 setTimeZone: [NSTimeZone systemTimeZone]];
}else{
[df2 setTimeZone:[NSTimeZone timeZoneWithName:fechaEnd.tzid]];
}
NSDate* parsedDateE = [df2 dateFromString: fechaEnd.fecha];
//rRules
NSString *rfc2445String = evento.rRule; // Usando la libreria EKRecurrenceRule+RRULE.m
EKRecurrenceRule *recurrenceRule;
if (![rfc2445String isEqualToString:#""]) {
recurrenceRule = [[EKRecurrenceRule alloc] initWithString:rfc2445String andTimezone:fechaStart.tzid];
// NSLog(#"RRule: %#", recurrenceRule);
}
if(parsedDateS!=nil){
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted) {
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = evento.summary;
event.notes = evento.description;
event.startDate = parsedDateS;
event.endDate = parsedDateE;
event.location = evento.location;
if (![rfc2445String isEqualToString:#""])
event.recurrenceRules = [NSArray arrayWithObject:recurrenceRule];
event.calendar = [eventStore calendarWithIdentifier: cal.calendarIdentifier];
//[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err = nil;
BOOL success = [eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
if(!success){
if (err) {
NSLog(#"Calendar was not set: %li %#", (long)err.code, err.description);
}
}else{
//NSLog(#"Added Event");
res = YES;
}
} else {
// code here for when the user does NOT allow your app to access the calendar
alerta = [[UIAlertView alloc]initWithTitle:AMLocalizedString(#"Error", #"")
message:AMLocalizedString(#"errorPermisosCal", #"")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alerta show];
}
}];
}else{
NSLog(#"The start date is null");
}
df = nil;
df2 = nil;
}else{
alerta = [[UIAlertView alloc]initWithTitle:AMLocalizedString(#"Error", #"")
message:AMLocalizedString(#"VersionEvento", #"")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alerta show];
}
return res;
}
Finally I have been able to perform the massive bulk of events without failures, I have modified the methods being as follows:
- (void) addCalendarEvents: (EKCalendar *) cal store: (EKEventStore *) eventStore {
if (!SYSTEM_VERSION_LESS_THAN(#"6.0")) {
// iOS 6 and later
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted) {
//se aƱade cada uno de los eventos
for (int i=0; i < [calendario.eventos count]; i++) {
#autoreleasepool {
NSDictionary * nextDict = [calendario.eventos objectAtIndex:i];
Evento_DTO * evento_dto = [[Evento_DTO alloc] initWithEventos:nextDict];
[self addEventCalendar: evento_dto calendar: cal.calendarIdentifier store: eventStore];
}
}
} else {
// code here for when the user does NOT allow your app to access the calendar
alerta = [[UIAlertView alloc]initWithTitle:AMLocalizedString(#"Error", #"")
message:AMLocalizedString(#"errorPermisosCal", #"")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alerta show];
}
}];
}else{
alerta = [[UIAlertView alloc]initWithTitle:AMLocalizedString(#"Error", #"")
message:AMLocalizedString(#"Event version", #"")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alerta show];
}
}
And the function that adds the event to the calendar is as follows:
-(void)addEventCalendar: (Evento_DTO *) evento calendar: (NSString *) cal store: (EKEventStore *) eventStore{
//Obtenemos las fechas del evento
Fecha_DTO *fechaStart = [[Fecha_DTO alloc] initWithFecha:(NSDictionary *)evento.dtStart];
Fecha_DTO *fechaEnd = [[Fecha_DTO alloc] initWithFecha:(NSDictionary *)evento.dtEnd];
// Format the dates to type NSDate
// Start Date
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyyMMdd'T'HHmmss"];
if (fechaStart.tzid == nil) {
[df setTimeZone: [NSTimeZone systemTimeZone]];
}else{
[df setTimeZone:[NSTimeZone timeZoneWithName:fechaStart.tzid]];
}
NSDate* parsedDateS = [df dateFromString: fechaStart.fecha];
// End Date
NSDateFormatter* df2 = [[NSDateFormatter alloc] init];
[df2 setDateFormat:#"yyyyMMdd'T'HHmmss"];
if (fechaEnd.tzid == nil) {
[df2 setTimeZone: [NSTimeZone systemTimeZone]];
}else{
[df2 setTimeZone:[NSTimeZone timeZoneWithName:fechaEnd.tzid]];
}
NSDate* parsedDateE = [df2 dateFromString: fechaEnd.fecha];
//rRules
NSString *rfc2445String = evento.rRule;
EKRecurrenceRule *recurrenceRule;
if (![rfc2445String isEqualToString:#""]) {
recurrenceRule = [[EKRecurrenceRule alloc] initWithString:rfc2445String andTimezone:fechaStart.tzid];
//NSLog(#"RRule: %#", recurrenceRule);
}
if(parsedDateS!=nil){
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = evento.summary;
event.notes = evento.description;
event.location = evento.location;
event.startDate = parsedDateS;
event.endDate = parsedDateE;
if (![rfc2445String isEqualToString:#""])
event.recurrenceRules = [NSArray arrayWithObject:recurrenceRule];
event.calendar = [eventStore calendarWithIdentifier: cal];
NSError *err = nil;
BOOL success = [eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
if(!success){
if (err) {
NSLog(#"Calendar was not set: %li %#", (long)err.code, err.description);
}
}else{
NSLog(#"Added Event");
}
}else{
NSLog(#"The start date is null");
}
df = nil;
df2 = nil;
}
I hope it helps somebody.

UILocalNotification applicationIconBadgeNumber not work when a day goes

Everything works fine with the following code if it is not change the day. But when change the day puts the badge 2 instead to put 1.
You know why this happens?
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = startDate;
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.alertBody = [NSString stringWithFormat:#"%# '%#'.", NSLocalizedString (#"Tiene tareas pendientes para realizar en su acuario", ""), descripcionAcuario];
localNotification.alertAction = descripcionTextField.text;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
NSDictionary *inventory = #{
#"AcuarioID" : [NSNumber numberWithInt: acuarioSeleccionadoID],
#"TareaID" : [NSNumber numberWithInt: tareaSeleccionada],
};
localNotification.userInfo= inventory;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
NSString *alarmTimeStr = [[NSString alloc]init];
alarmTimeStr = [NSString stringWithFormat:#"%#",alarmTimeTextField.text];
NSDate *pickerdate = dateTimePicker.date;
[[NSCalendar currentCalendar] rangeOfUnit:NSMinuteCalendarUnit
startDate:&pickerdate
interval:NULL
forDate:pickerdate];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
pickerDate1 = pickerdate;
finaldate =pickerDate1;
// ** Local notification Assignment **
localNotification = [[UILocalNotification alloc] init];
if (localNotification == nil)
return;
localNotification.fireDate = pickerDate1;
localNotification.alertBody = alarmNameTextField.text;
localNotification.alertAction = #"OK";
localNotification.soundName = [NSString stringWithFormat:#"%#.mp3",alarmTonesTextField.text];
localNotification.timeZone = [NSTimeZone systemTimeZone];
[localNotification setHasAction:YES];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[self setalarm];
-(void)setalarm
{
if ([sunValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:1];
[self setweek];
}
if ([monValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:2];
[self setweek];
}
if ([tueValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:3];
[self setweek];
}
if ([wedValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:4];
[self setweek];
}
if ([thuValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:5];
[self setweek];
}
if ([friValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:6];
[self setweek];
}
if ([satValue isEqualToString:#"1"])
{
finaldate =pickerDate1;
[self getDateOfSpecificDay:7];
[self setweek];
}
alarmArray = [[DBManager sharedDatabase] getAlarmsDetail];
if ([alarmArray count] != 0)
{
[self showAllAlarmsInAlarmView];
}
if ([alarmArray count]==0)
{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
}
-(void)setweek
{
#try
{
NSDateFormatter *formatterdate=[[NSDateFormatter alloc]init];
[formatterdate setDateFormat:#"YYYY-MM-dd"];
NSDateFormatter *formattertime =[[NSDateFormatter alloc]init];
[formattertime setDateFormat:#"HH:mm:ss"];
NSString * stringdate = [NSString stringWithFormat:#"%#",resultDate];
NSString *stringdate123 =[stringdate substringToIndex:10];
NSString *stringtime =[dateFormatter stringFromDate:pickerDate1];
NSString * stringtime123 =[stringtime substringFromIndex:11];
NSString * stringdate1234=[stringdate123 stringByAppendingString:#" "];
NSString * stringdate12345=[stringdate1234 stringByAppendingString:stringtime123];
finaldate =[dateFormatter dateFromString:stringdate12345];
localNotification = [[UILocalNotification alloc] init];
if (localNotification == nil)
return;
localNotification.fireDate = finaldate;
localNotification.alertBody = alarmNameTextField.text;
localNotification.repeatInterval =NSWeekCalendarUnit;
localNotification.alertAction = #"OK";
localNotification.soundName = [NSString stringWithFormat:#"%#.mp3",alarmTonesTextField.text];//#"Jai Hanuman.mp3";
localNotification.timeZone = [NSTimeZone systemTimeZone];
[localNotification setHasAction:YES];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
#catch (NSException *exception)
{
[[saveClass shared_class] writeStringToFile:#"alarmViewController" andfunctionname:#"saveAlarmAndSetNotification" andexception:(NSString*)exception];
}
#finally
{}
}
-(NSDate *) getDateOfSpecificDay:(NSInteger ) day /// here day will be 1 or 2.. or 7
{
NSInteger desiredWeekday = day;
NSRange weekDateRange = [[NSCalendar currentCalendar] maximumRangeOfUnit:NSWeekdayCalendarUnit];
NSInteger daysInWeek = weekDateRange.length - weekDateRange.location + 1;
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:finaldate];
NSLog(#"%#",[NSDate date]);
NSInteger currentWeekday = dateComponents.weekday;
if (desiredWeekday == currentWeekday)
{
differenceDays = 7;
daysComponents = [[NSDateComponents alloc] init];
}
else
{
differenceDays = (desiredWeekday - currentWeekday + daysInWeek) % daysInWeek;
daysComponents = [[NSDateComponents alloc] init];
}
daysComponents.day = differenceDays;
resultDate = [[NSCalendar currentCalendar] dateByAddingComponents:daysComponents toDate:finaldate options:0];
return resultDate;
}

Repeat Functionality in Alarm

I am new to iOS. I am making an alarm application and I want to implement the repeat functionality. I search a lot and didn't understand much how to do this. I know it is done by notification method. I am stuck with it . Please anyone tell me the solution. Here is my code when user save the alarm.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeZone = [NSTimeZone defaultTimeZone];
NSLog(#"dateformater %#",dateFormatter);
dateFormatter.timeStyle = NSDateFormatterShortStyle;
NSString * dateTimeString = [dateFormatter stringFromDate:timePicker.date];
NSLog(#"date time string %#",dateTimeString);
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:NSLocaleIdentifier]];
//[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
datesArray = #[[dateFormatter stringFromDate:self.timePicker.date]];
NSLog(#"dates array is %#",datesArray);
[datesArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
NSArray * repeatDays = [repeatResult componentsSeparatedByString:#","];
for (NSString * days in repeatDays)
{
if ([days isEqualToString:#"Sun"])
{
[self getDateOfSpecificDay:1];
}
if ([days isEqualToString:#"Mon"])
{
[self getDateOfSpecificDay:2];
}
if ([days isEqualToString:#"Tue"])
{
[self getDateOfSpecificDay:3];
}
if ([days isEqualToString:#"Wed"])
{
[self getDateOfSpecificDay:4];
}
if ([days isEqualToString:#"Thu"])
{
[self getDateOfSpecificDay:5];
}
if ([days isEqualToString:#"Fri"])
{
[self getDateOfSpecificDay:6];
}
if ([days isEqualToString:#"Sat"])
{
[self getDateOfSpecificDay:7];
}
}
}];
AlarmObject * alarm = [[AlarmObject alloc] init];
alarm.repeatData = repeatResult;
alarm.clockDate = dateTimeString;
[self.delegate alarmSetting:alarm];
[self scheduleLocalNotificationWithDate:timePicker.date];
[self.navigationController popViewControllerAnimated:YES];
and here is my scheduledLocalNotification mehtod
-(void) scheduleLocalNotificationWithDate:(NSDate *)fireDate
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
localNotif.alertBody = #"Time to wake Up";
localNotif.alertAction = #"Show me";
localNotif.soundName = #"Tick-tock-sound.mp3";
localNotif.applicationIconBadgeNumber = 1;
localNotif.repeatInterval = NSCalendarUnitWeekOfYear;
NSLog(#"%#",[NSDate date]);
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];`
I'm stuck with it from past 4 days. I know my question is duplicate but I am not sure how implement that logic. Thanks in advance.
Change the
dateFormatter.timeZone = [NSTimeZone defaultTimeZone];
to
dateFormatter.timeZone = [NSTimeZone localTimeZone];
and check out this tutorial for repeat fucntionailty.

Find out next most close date from NSDate array of times

How can I find out the next prayer from the array of times, I have total 6 Prayers at different times and i want to compare each one with current time and have to find out which one is most near as a next prayer, Date format also creating problems because it give always in UTC format and I have to use local time zone, I am using the following code:
NSMutableArray *arrayTimeIntervals = [[NSMutableArray alloc]init];
NSMutableArray *intervals = [[NSMutableArray alloc]init];
NSMutableArray *arrayPrayers = [[NSMutableArray alloc]init];
[arrayPrayers addObject:#{#"prayer":#"prayer 1",#"time":#"1:12 am"}];
[arrayPrayers addObject:#{#"prayer":#"prayer 2",#"time":#"5:45 am"}];
[arrayPrayers addObject:#{#"prayer":#"prayer 3",#"time":#"12:03 pm"}];
[arrayPrayers addObject:#{#"prayer":#"prayer 4",#"time":#"3:30 pm"}];
[arrayPrayers addObject:#{#"prayer":#"prayer 4",#"time":#"6:20 pm"}];
[arrayPrayers addObject:#{#"prayer":#"prayer 6",#"time":#"7:50 pm"}];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm a"];
NSMutableArray *dates = [NSMutableArray arrayWithCapacity:arrayPrayers.count];
for (NSDictionary *timeDict in arrayPrayers)
{
NSString *timeString = [timeDict objectForKey:#"time"];
NSString *name = [timeDict objectForKey:#"prayer"];
NSDate *date = [dateFormatter dateFromString:timeString];
[dates addObject:#{#"prayer":name,#"time":timeString, #"date":date}];
}
for (int i =0 ; i<arrayPrayers.count; i++) {
NSDictionary *timeDict = arrayPrayers[i];
NSString *timeString = [timeDict objectForKey:#"time"];
//NSString *name = [timeDict objectForKey:#"prayer"];
NSDate *date = [dateFormatter dateFromString:timeString];
NSComparisonResult result = [[NSDate date] compare:date];
if(result==NSOrderedAscending){
NSLog(#"next prayer");
}else if(result==NSOrderedDescending){
NSLog(#"last prayer");
}else{
NSLog(#"current prayer");
}
if ([date earlierDate:[NSDate date]]) {
NSTimeInterval interval = [date timeIntervalSinceNow];
NSDictionary *tempDict = #{#"Prayer":timeDict,
#"Time":timeString,
#"Index":[NSString stringWithFormat:#"%d",i],
#"Interval":[NSString stringWithFormat:#"%f",interval]};
[arrayTimeIntervals addObject:tempDict];
[intervals addObject:[NSString stringWithFormat:#"%f",interval]];
}
}
NSNumber * min = [intervals valueForKeyPath:#"#min.doubleValue"];
NSUInteger index = 0;
for(int i =0 ; i<intervals.count; i++)
{
NSDictionary* dict = arrayTimeIntervals[i];
if([[dict objectForKey:#"Interval"] intValue] == [min intValue]) {
index = i;
NSLog(#"next prayer is!!!:%ld",index);
break;
}
}
NSDictionary *dict = [arrayTimeIntervals objectAtIndex:index];
NSLog(#"next prayer object is:%#",dict);

How to correctly generate timestamp

I have a method that to create timestamp in long long integer format
EX: 1386752892
+ (NSNumber *)currentTimestampWithLongLongFormat
{
double timeStamp = ceil([[NSDate date] timeIntervalSince1970] * 1000);
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setGeneratesDecimalNumbers:false];
NSNumber *timeNumber = [NSNumber numberWithDouble:timeStamp];
NSString *timeString = [formatter stringFromNumber:timeNumber];
// NSTimeInterval is defined as double
return [NSNumber numberWithLongLong:[timeString longLongValue]];
}
But this will generate 13 digitals number
EX: 1386752811802
How to fix the problem and generate the correct format of number?
int timestamp = [[NSDate date] timeIntervalSince1970];
Try this
/**
* #param nil
* #return current time in mili second
*
* Fetch the current time stamp
*/
-(NSString *)currentTimeStamp {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithName:#"GMT"];
[dateFormatter setTimeZone:gmt];
NSString *timeStamp1 = [dateFormatter stringFromDate:[NSDate date]];
NSDate *curdate = [dateFormatter dateFromString:timeStamp1];
double unix_timestamp = [curdate timeIntervalSince1970];
NSString *timeStamp = [NSString stringWithFormat:#"%f",unix_timestamp*1000];
return timeStamp;
}
+ (NSString*) dateFromString:(NSString*)aStr
{
NSDateFormatter *formater = [[NSDateFormatter alloc] init];
[formater setDateFormat:#"yyyy-MM-dd HH:mm"];
NSDate *date2 = [formater dateFromString:aStr];
[formater setDateFormat:#"d MMM,yyyy HH:mm"];
NSString *result = [formater stringFromDate:date2];
return result;
}
+ (NSString *)calculateTime:(NSString *)datetime :(NSString *)servertime
{
NSString *time;
NSDate *date1;
NSDate *date2;
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
date1 = [formatter dateFromString:datetime];
date2 = [formatter dateFromString:servertime];
}
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *differenceComponents = [calendar components:(NSDayCalendarUnit)
fromDate:date1
toDate:date2
options:0];
NSTimeInterval interval = [date1 timeIntervalSinceDate: date2];//[date1 timeIntervalSince1970] - [date2 timeIntervalSince1970];
int hour = interval / 3600;
int minute = (int)interval % 3600 / 60;
int seconds = (int)interval % 60;
hour=ABS(hour);
minute=ABS(minute);
seconds=ABS(seconds);
if ([differenceComponents day]>0) {
time= [NSString stringWithFormat:#"%ld %#", (long)[differenceComponents day],[NSString stringWithFormat:NSLocalizedString(#"daysago", nil)]];
}
else
{
if ([differenceComponents day] == 0) {
time= [NSString stringWithFormat:#"%ld %#", (long)[differenceComponents day],[NSString stringWithFormat:NSLocalizedString(#"dayago", nil)]];
if (hour>0) {
time= [NSString stringWithFormat:#"%d %#", ABS(hour),[NSString stringWithFormat:NSLocalizedString(#"hourago", nil)]];
}
else {
time= [NSString stringWithFormat:#"%d %#", ABS(hour),[NSString stringWithFormat:NSLocalizedString(#"hoursago", nil)]];
if (minute>0) {
time= [NSString stringWithFormat:#"%d %#", ABS(minute),[NSString stringWithFormat:NSLocalizedString(#"minuteago", nil)]];
}
else {
time= [NSString stringWithFormat:#"%d %#", ABS(minute),[NSString stringWithFormat:NSLocalizedString(#"minuteago", nil)]];
if (seconds>0) {
time= [NSString stringWithFormat:#"%d %#", ABS(seconds),[NSString stringWithFormat:NSLocalizedString(#"secondago", nil)]];
}
else {
time= [NSString stringWithFormat:#"%d %#", ABS(seconds),[NSString stringWithFormat:NSLocalizedString(#"secondsago", nil)]];
}
}
}
}
}
return time;
}
/// as per requirement we will use date formats

Resources