ios - 实现 NSURLConnection 委托(delegate)

标签 ios objective-c asynchronous nsurlconnection

我是网络服务的新手。 我正在尝试实现此协议(protocol),但我有一些问题:

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

最佳答案

对于异步请求,您可以使用。

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

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

相关文章:

ios - 如何使用 NSPredicate 查找数组中具有特定属性的对象?

ios - NSMutableAttributedString斜体和粗体不能同时工作

ios - 如何在 web-view swift 中设置代理?

objective-c - 将随机生成的 NSString 添加到 NSMutableArray 的算法

objective-c - 排序标题

objective-c - 如何在 awakeFromNib 中打开 NSAlert? (注意窗口动画)

vb.net 服务器 - 多个客户端不断处理不同的信息

iphone - 如何将 NSArray 发送到 Web 服务

javascript - 在Javascript的Promise中,为什么不能将错误传递给下一个链 `.catch()` ?

.net - .NET 中的异步 WMI 事件处理