// Starts a connection to download the current URL.
- (void)_startReceive
{
NSURL * url;
NSURLRequest * request;
app_Delegate.email=[[NSUserDefaults standardUserDefaults] objectForKey:@"emailKey"];
app_Delegate.idScore=[[NSUserDefaults standardUserDefaults] valueForKey:@"IDC2i"];
if ( (app_Delegate.email==nil) || [app_Delegate.email isEqualToString:@""]) //Envoi d'un requête HTTP sans email
{
//création de l'url
NSString * tmp = [NSString stringWithFormat:@"%@%@",app_Delegate.plateforme,app_Delegate.getAnonyme];
url = [NSURL URLWithString: tmp];
//création de la requête
request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
assert(request!=nil);
if (connexion)
{
[connexion release], connexion = nil;
}
connexion = [NSURLConnection connectionWithRequest:request delegate:self];
assert(connexion!=nil);
}
else if (app_Delegate.email !=nil || ![app_Delegate.email isEqualToString:@""])//Envoi d'une requête HTPP avec email
{
//création de l'url
NSString * tmp = [NSString stringWithFormat:@"%@%@&email=%@",app_Delegate.plateforme,app_Delegate.getAnonyme,app_Delegate.email];
url = [NSURL URLWithString: tmp];
//création de la requête
request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
assert(request!=nil);
if (connexion)
{
[connexion release], connexion = nil;
}
connexion = [NSURLConnection connectionWithRequest:request delegate:self];
assert(connexion!=nil);
}
//Tell the UI we're receiving
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
connectingAlert = [[WheelAlertView alloc] initWithTitle:NSLocalizedString(@"connexion", @"")
message:@""
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:nil];
[connectingAlert addWheel];
[connectingAlert show];
if (donneeExamen)
{
[donneeExamen release], donneeExamen = nil;
}
donneeExamen = [[NSMutableData data] retain];
}
// Shuts down the connection and displays the result (statusString == nil)
// or the error status (otherwise).
//méthode qui se lance si auncune connexion
- (void)_stopReceiveWithStatus:(NSString *)statusString
{
//on stoppe la connexion
if (connexion != nil) {
[connexion cancel];
connexion = nil;
}
//on stop l'indicateur d'activité reseau
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//on ferme le wheelAlertView
[connectingAlert close];
UIAlertView * alerte=[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", @"") message:statusString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alerte show];
[alerte release];
}
// A delegate method called by the NSURLConnection when the request/response
// exchange is complete. We look at the response to check that the HTTP
// status code is 2xx and that the Content-Type is acceptable. If these checks
// fail, we give up on the transfer.
- (void)connection:(NSURLConnection *)theConnection didReceiveResponse:(NSURLResponse *)response
{
#pragma unused(theConnection)
NSHTTPURLResponse * httpResponse;
NSString * contentTypeHeader;
assert(theConnection == self.connexion);
httpResponse = (NSHTTPURLResponse *) response;
assert( [httpResponse isKindOfClass:[NSHTTPURLResponse class]] );
if ((httpResponse.statusCode / 100) != 2) {
[self _stopReceiveWithStatus:[NSString stringWithFormat:@"erreur HTTP %zd", (ssize_t) httpResponse.statusCode]];
}
else
{
contentTypeHeader = [httpResponse.allHeaderFields objectForKey:@"Content-Type"];
NSString * regex = @"(text/html)|(text/xml)";
if (contentTypeHeader == nil)
{
[self _stopReceiveWithStatus:@"Mauvais type de contenu"];
}
else if ( ![contentTypeHeader isMatchedByRegex:regex] )
{
[self _stopReceiveWithStatus:[NSString stringWithFormat:@"Type de contenu non supporté (%@)", contentTypeHeader]];
}
else
{
[connectingAlert setTitle:NSLocalizedString(@"connexionEffectuee", @"")];
/*donneeExamen = [[NSMutableData alloc] init];
donneeExamen = [[NSMutableData data] retain];*/
[donneeExamen setLength:0];
}
}
}
// A delegate method called by the NSURLConnection as data arrives. We just
// write the data to the file.
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data
{
#pragma unused(theConnection)
assert(theConnection == connexion);
[donneeExamen appendData:data];//A ce moment donneeExamen ne contient que des bits
[connectingAlert setTitle:NSLocalizedString(@"Reception de l'examen",@"")];
}
// A delegate method called by the NSURLConnection if the connection fails.
// We shut down the connection and display the failure. Production quality code
// would either display or log the actual error
- (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error
{
#pragma unused(theConnection)
#pragma unused(error)
assert(theConnection == connexion);
[self _stopReceiveWithStatus:[NSString stringWithFormat:@"%@",[error localizedDescription]]];
}
// A delegate method called by the NSURLConnection when the connection has been
// done successfully. We shut down the connection with a nil status, which
// causes the image to be displayed.
- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection
{
#pragma unused(theConnection)
assert(theConnection == self.connexion);
//on annule la connexion
if (connexion != nil) {
[connexion cancel];
connexion = nil;
}
//on arrete l'indicateur d'activité réseau
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//On décode donneeExamen en string
NSString * lesDonnees = [[NSString alloc] initWithBytes: [donneeExamen mutableBytes] length:[donneeExamen length] encoding:NSUTF8StringEncoding];
//On ferme le wheelAlertView
[connectingAlert close];
//On tranforme lesDonnees au format JSON
NSDictionary * jsonResults = [lesDonnees JSONValue];
if ([[jsonResults objectForKey:@"error"] isEqualToString:@"Pas d'examen anonyme autorisé ou en cours"])
{
UIAlertView *actionSheet = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"PasDePositionnementAnonyme",@"") message:NSLocalizedString(@"PasDePositionnementAnonymeMessage",@"")delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[actionSheet show];
[actionSheet release];
[lesDonnees release],lesDonnees = nil;
[donneeExamen release], donneeExamen = nil;
return;
}
if (jsonResults == nil) //Si jsonResults ne contient rien, on affiche une erreur
{
UIAlertView *actionSheet = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Problème de récupération des données",@"") message:NSLocalizedString(@"mauvaise réception de l'examen",@"")delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[actionSheet show];
[actionSheet release];
}
else //sinon on peut lancer l'examen
{
[app_Delegate lancementExamen:jsonResults];
}
[donneeExamen release], donneeExamen = nil;
[lesDonnees release],lesDonnees = nil;
}
In the appDelegate :
Code:
- (void) lancementExamen:(NSDictionary *) data
{
dataAppDelegate=[data retain];
[self.window.superview removeFromSuperview];
[self.tabBarController.view removeFromSuperview];
//on alloue une vue de type ExamenViewController qui est en faite une UITableVIewController
if (examenViewController)
{
[examenViewController release], examenViewController = nil;
}
examenViewController = [[ExamenViewController alloc] initWithInterface];
[examenViewController UpDateData:dataAppDelegate];
//on alloue un UINavigationController avec comme root : exameView
UINavigationController * tmpNavigationController = [[UINavigationController alloc] initWithRootViewController:examenViewController];
navigationController = [tmpNavigationController retain];
self.navigationController.toolbarHidden=NO;
self.navigationController.toolbar.barStyle=UIBarStyleBlack;
[self.window addSubview:[navigationController view]];
[tmpNavigationController release];
}