Question

I'm new to the Network service. I'm trying to implement this protocole and I have some question :

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"connection didReceiveResponse");
    _responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"connection didReceiveData");
    [self.responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse
{
    // Retourne nil pour indiquer qu'il n'est pas nécessaire de stocker les réponses en cache pour cette connexion
    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    // Si on a reçu des données, on peut parser
    if(self.responseData.length > 0)
    {
        NSLog(@"connectionDidFinishLoading lenght data = %i", self.responseData.length);
        NSError **parseError = nil;

        self.myDictionnaryData = [NSJSONSerialization JSONObjectWithData:self.responseData
                                                             options:0
                                                               error:parseError];

        if(parseError != nil)
            NSLog(@"Erreur lors du parse des données");
    }

    self.finished = YES;

}

// Appelé s'il y a une erreur related to the URL connection handling / server response.
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    self.finished = YES;
    NSLog(@"connection didFailWithError");
}

but I have a problem : The first redirect doesn't works ..

-(IBAction)submitForm:(id)sender
 {
 self.finished = NO;


// On met l'url avec les variables sous forme de chaine de caractere
NSString *post =[NSString stringWithFormat:@"login=%@&pwd=%@&regid=%@&platform=%@&version=%@",self.identifying,self.password,token,platform,systemVersion];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

NSMutableURLRequest *request = [ [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URL_LOGIN_API]] autorelease];
[request setHTTPMethod:@"POST"]; // de type post
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

[NSURLConnection connectionWithRequest:request delegate:self];

while(!self.finished) {
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}

    [NSURLConnection connectionWithRequest:request delegate:self];

This is my connection. When I redirect the first time, all the object in my dictionary are null, when I re-try it, it's ok .. It seems the method are called after the request

EDIT : It works if I add something like :

while(!self.finished) {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }

and

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"connectionDidFinishLoading");
NSError **parseError = nil;
self.myDictionnaryData = [NSJSONSerialization JSONObjectWithData:self.responseData
                                                         options:0
                                                           error:parseError];

if(parseError != nil)
{
    NSLog(@"Erreur lors du parse des données");
}

self.finished = YES;
}
Était-ce utile?

La solution 2

This code is ill conceived:

[NSURLConnection connectionWithRequest:request delegate:self];

while(!self.finished) {
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}

NSArray *last_name = [[self.myDictionnaryData objectForKey:@"data"] valueForKey:@"lastname"];

Because once you start the connection you should not be waiting for the response is a loop. The response is asynchronous so you should use it when it becomes available in connectionDidFinishLoading:. Move all of your handling code to there (or, better, to a method called from there).


Other issues:

You shouldn't be doing this:

_myDictionnaryData = [[NSMutableDictionary alloc] init];

(because you will never use that instance before it is replaced). And don't just move it to your init method as that has the same issue. And in your init method you need to call super before you try to set and instance variable content.

or this:

[*parseError release];

(because the error isn't yours to release).

Other than that your code is fine. This is asynchronous by its nature because it's using delegate methods, and the top level documentation for NSURLConnection describes how it is an asynchronous operation.

didFailWithError: will be called with any error related to the URL connection handling / server response.

Autres conseils

For Asynchronous Request you can use.

NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:url_string]]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue currentQueue]
 completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
     NSString *returnString1  = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
     NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[returnString1 dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];}];

I use OHURLLoader, ist depends on NSURLConnection, and is easy to use.

https://github.com/AliSoftware/OHURLLoader

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top