reloj problema posicion porque poner pantalla hora formato fecha desconfigura como cambiar año atrasa apple ios xcode

ios - problema - Obtenga fecha y hora de Apple Server



porque se desconfigura la hora de mi iphone (6)

Aquí está mi código, usando 2 servicios web diferentes en caso de que uno de ellos esté fuera de servicio:

NSString *urlString = [NSString stringWithFormat:@"http://date.jsontest.com"]; NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSData *data = [[NSData alloc] initWithContentsOfURL:url]; NSError *error; NSNumber *milliSecondsSince1970 = nil; if (data != nil) { NSDictionary *json =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; milliSecondsSince1970 = [json valueForKey:@"milliseconds_since_epoch"]; NSLog(@"milliSecondsSince1970 = %@", milliSecondsSince1970); } else { urlString = [NSString stringWithFormat:@"https://currentmillis.com/time/seconds-since-unix-epoch.php"]; url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; data = [[NSData alloc] initWithContentsOfURL:url]; if (data!=nil) { NSString *dbleStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; double dble = [dbleStr doubleValue]*1000; milliSecondsSince1970 = [NSNumber numberWithDouble:dble]; NSLog(@"milliSecondsSince1970 currentMillis = %@", milliSecondsSince1970); } else { double dateIntervalInSecondsSince1970 = [NSDate date].timeIntervalSince1970*1000; milliSecondsSince1970 = [NSNumber numberWithDouble:dateIntervalInSecondsSince1970] ; NSLog(@"milliSecondsSince1970 NSDate = %@", milliSecondsSince1970); } }

Estoy desarrollando una aplicación que solo se puede utilizar durante un determinado momento del día. No puedo obtener la hora local del dispositivo porque el usuario puede cambiar fácilmente la hora del dispositivo, permitiendo el acceso a la aplicación en cualquier momento del día.

¿Hay alguna forma de obtener la fecha y hora actuales de un servidor Apple (o, si no es así), hay alguna otra forma?


Creo que deberías estar usando un servidor de tiempo de Internet. Están utilizando un protocolo estandarizado llamado NTP . El iOS tiene soporte incorporado para leer la hora del servidor NTP , pero usted no puede acceder a este como desarrollador de aplicaciones. O implementa esto usted mismo, o podría usar una biblioteca de código abierto, como ios-ntp o HS NTP . Yo no he usado ninguno de ellos. Probablemente sea una buena idea verificar la posición del dispositivo y determinar la zona horaria para obtener una solución real a prueba de balas.

Aquí puedes leer más sobre los servidores y esas cosas; NIST Internet Time Service

Idealmente, debería tener una lista de servidores en la aplicación. Si uno de ellos falla, llame al siguiente servidor NTP de la lista.


Creo que su requerimiento puede ser cumplido por algunos servicios web que devuelven datos json.

Uno de ellos es jsontest.com: http://date.jsontest.com . Esto es lo que devuelve:

{ "time": "02:11:29 AM", "milliseconds_since_epoch": 1513563089492, "date": "12-18-2017" }

Los "milisegundos_since_epoch" representan milisegundos desde 1970, por lo que es fácil de convertir a Fecha, usando Date.init(timeIntervalSince1970: milliseconds_since_epoch/1000) . Luego podemos usar la clase Calendar para obtener la hora local.


La respuesta de Karan tuvo algunos errores tipográficos y tampoco pudo verificar una respuesta de "0" en lugar de solo "nil". (Lo implementé en mi aplicación y obtuve varios falsos positivos de conexiones débiles o redes no autorizadas).

Lo he adaptado a continuación y he agregado el código de servidor correspondiente para aquellos que no saben a qué se refería Karan. Esto se implementa como un método de categoría en una extensión NSDate, por lo que puede llamarlo usando [NSDate verifiedDate];

+(NSDate*)verifiedDate { if([self hasInternetConnectivity]) { NSURL *scriptUrl = [NSURL URLWithString:@"http://[yourwebsite].com/timestamp.php"]; NSData *data = [NSData dataWithContentsOfURL: scriptUrl]; if(data != nil) { NSString *tempString = [NSString stringWithUTF8String:[data bytes]]; if([tempString doubleValue] > 946684800) { // Date is at least later than 2000 AD, or else something went wrong NSDate *currDate = [NSDate dateWithTimeIntervalSince1970:[tempString doubleValue]]; NSLog(@"verifiedDate: String returned from the site is: %@ and date is: %@", tempString, [currDate description]); return currDate; } else { NSLog(@"verifiedDate: Server returned false timestamp (%@)", tempString); return [NSDate date]; } } else { NSLog(@"verifiedDate: NSData download failed"); return [NSDate date]; } } else { NSLog(@"verifiedDate: InternetConnectivity failed"); return [NSDate date]; } }

Y aquí está el código del servidor, almacenado en la carpeta raíz de su servidor como "timestamp.php"

<?php echo(time()); ?>


Puede usar ese código abierto para obtener tiempo del servidor NTP predeterminado, o elegir su servidor: https://github.com/huynguyencong/NHNetworkTime

[[NHNetworkClock sharedNetworkClock] syncWithComplete:^{ NSLog(@"%s - Time synced %@", __PRETTY_FUNCTION__, [NSDate networkDate]); }];

Y use:

NSDate *networkDate = [NSDate networkDate];


- (NSDate *) CurrentDate { if ([self hasInternetConnectivity]) // this tests Internet connectivity based off Apple''s Reachability sample code { NSSURL * scriptUrl = [NSURL URLWithString: @"http:// <yoursite>. Com / <the 2 line php script>. Php"]; NSData * data = [NSData dataWithContentsOfURL: scriptUrl]; if (data! = nil) { NSString * tempString = [NSString stringWithUTF8String: [data bytes]]; NSDate * currDate = [NSDate dateWithTimeIntervalSince1970: [tempString doubleValue]]; NSLog (@ "String returned from the site is:% @ and date is:% @", tempString, [currDate description]); return currDate; } else { NSLog (@ "nsdata download failed"); return [NSDate date]; } } else { NSLog (@ "InternetConnectivity failed"); return [NSDate date]; } }