首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >实现NSURLConnectionDelegate

实现NSURLConnectionDelegate
EN

Stack Overflow用户
提问于 2014-04-08 09:28:12
回答 3查看 117关注 0票数 0

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

代码语言:javascript
复制
    - (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");
}

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

代码语言:javascript
复制
-(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];

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

编辑:如果我添加了如下内容,它就会工作:

代码语言:javascript
复制
while(!self.finished) {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }

代码语言:javascript
复制
- (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;
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-04-08 09:48:10

这一守则构思不当:

代码语言:javascript
复制
[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:中可用时,您应该使用它。将所有处理代码移到那里(或者更好地说,移到从那里调用的方法)。

其他问题:

你不应该这样做:

代码语言:javascript
复制
_myDictionnaryData = [[NSMutableDictionary alloc] init];

(因为在替换该实例之前,您永远不会使用它)。不要仅仅将它移到您的init方法中,因为这有相同的问题。在init方法中,在尝试设置和实例变量内容之前,需要调用super

或者这个:

代码语言:javascript
复制
[*parseError release];

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

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

将使用与didFailWithError:连接处理/服务器响应相关的任何错误调用。

票数 0
EN

Stack Overflow用户

发布于 2014-04-08 09:42:04

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

代码语言:javascript
复制
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];}];
票数 1
EN

Stack Overflow用户

发布于 2014-04-08 09:34:46

我使用OHURLLoader,ist依赖于NSURLConnection,而且很容易使用。

https://github.com/AliSoftware/OHURLLoader

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22932907

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档