实现NSURLConnectionDelegate

实现NSURLConnectionDelegate

我是网络服务的新手。
我正在尝试实施此协议,但我有一个问题:

    - (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");
}


但我有一个问题:第一次重定向不起作用..

-(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];


这是我的联系。第一次重定向时,字典中的所有对象都为空,当我重试时,可以..
 似乎在请求后调用了该方法

编辑:如果我添加类似的东西,它将起作用:

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




- (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;
}

最佳答案

这段代码构思不当:

[NSURLConnection connectionWithRequest:request delegate:self];

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

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


因为一旦启动连接,您就不必等待响应就是循环。该响应是异步的,因此在connectionDidFinishLoading:中可用时应使用它。将所有处理代码移到那里(或者更好的是,从那里调用一个方法)。



其他问题:

您不应该这样做:

_myDictionnaryData = [[NSMutableDictionary alloc] init];


(因为在替换实例之前您将永远不会使用该实例)。并且不要将其移至您的init方法,因为那样会出现相同的问题。并且在您的init方法中,您需要在尝试设置和实例变量内容之前调用super

或这个:

[*parseError release];


(因为该错误不是您要发布的)。

除此之外,您的代码还可以。这是异步的,因为它使用委托方法,并且NSURLConnection的顶级文档描述了它如何是异步操作。

didFailWithError:会被调用,并且会出现与URL连接处理/服务器响应有关的任何错误。

关于ios - 实现NSURLConnectionDelegate,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22932907/

10-09 06:29