【问题标题】:NSURLConnection doesn't receive dataNSURLConnection 不接收数据
【发布时间】:2012-08-01 07:06:55
【问题描述】:

我已经实现了一个NSURLConnection,它向服务器发送请求并接收一些存储在NSMutableData 对象中的数据。这些是我作为NSURLConnectionDelegate 的一部分实现的方法:

-(void)upLoadBook:(NSMutableDictionary *)theOptions{

NSMutableString *theURL = [[NSMutableString alloc] initWithString:@"theURL"];

[theURL appendFormat:@"&Title=%@&Author=%@&Price=%@",  [theOptions objectForKey:@"bookTitle"], 
                                                       [theOptions objectForKey:@"bookAuthor"], 
                                                       [theOptions objectForKey:@"bookPrice"]];
[theURL appendFormat:@"&Edition=%@&Condition=%@&Owner=%@", [theOptions objectForKey:@"bookEdition"],
                                                        [theOptions objectForKey:@"bookCondition"],
                                                        _appDel.userID];

NSLog(@"%@\n", theURL);
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:theURL]
                                            cachePolicy:NSURLRequestUseProtocolCachePolicy
                                        timeoutInterval:10.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
    // Create the NSMutableData to hold the received data.
    // receivedData is an instance variable declared elsewhere.
    receivedData = [NSMutableData data];
}
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
   [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse      
  *)response
 {
// This method is called when the server has determined that it
// has enough information to create the NSURLResponse.

// It can be called multiple times, for example in the case of a
// redirect, so each time we reset the data.

// receivedData is an instance variable declared elsewhere.
[receivedData setLength:0];
}

 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
   // do something with the data
  // receivedData is declared as a method instance elsewhere

//Receives a response after book has been uploaded (Preferably a Book ID...)
  responseString = [[NSString alloc] initWithData:receivedData         
 encoding:NSUTF8StringEncoding];

NSLog(@"Response String: %@", responseString);
[_options setValue:responseString forKey:@"bookID"];

[self performSegueWithIdentifier:@"UploadSuccessSegue" sender:self];

}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Whoops." message:@" No internet     
connection.\n Please make sure you have a connection to the internet." 
                                               delegate:self cancelButtonTitle:@"Ok"   
otherButtonTitles: nil];
[alert show];
}

函数uploadBook 似乎被调用,但是,我从来没有到达didFinishLoadingdidReceiveData 从来没有收到任何数据。可能是什么问题。任何提示或线索将不胜感激。

【问题讨论】:

    标签: iphone ios nsurlconnection nsurlconnectiondelegate


    【解决方案1】:

    您需要将您的 NSURLConnection 添加到当前运行循环或单独的一个(例如您在单独的线程中设置的一个)。毕竟,委托方法确实需要获取 CPU 时间。

    Looking at this related question's accepted answer,也可以通过Grand Central Dispatch:

    dispatch_async(dispatch_get_main_queue(), ^{
        NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
        [conn start];
    });
    

    【讨论】:

    • 可能就是这样。我该怎么做呢?
    【解决方案2】:

    可以肯定的是,在尝试发送请求之前,您应该 %-escape 您的参数列表。

    您可以为此目的使用stringByAddingPercentEscapesUsingEncoding

    NSMutableString *theURL = [[NSMutableString alloc] initWithString:@""];
    
    [theURL appendFormat:@"&Title=%@&Author=%@&Price=%@",  [theOptions objectForKey:@"bookTitle"], 
                                                       [theOptions objectForKey:@"bookAuthor"], 
                                                       [theOptions objectForKey:@"bookPrice"]];
    [theURL appendFormat:@"&Edition=%@&Condition=%@&Owner=%@", [theOptions objectForKey:@"bookEdition"],
                                                        [theOptions objectForKey:@"bookCondition"],
                                                        _appDel.userID];
    
    
     theURL = [NSStringWithFormat:@"YOUR_URL_HERE?",[theURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    

    请注意,我以最少的更改次数重构了您的代码以获得结果。你肯定能找到更好的重构。

    【讨论】:

    • 请看我上次的编辑,我为转义指定了错误的函数。
    • 我 +1 了,因为你提出了一个很好的观点,而且比我还快:-)
    • 好的,我也会实现这个。由于@Michael 已经回答了我的直接问题,我将接受他作为官方答案,但我会支持此评论。
    【解决方案3】:

    这是我的一个项目的示例:

    NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.brayden.me/analytics/device.php"]];
    [urlRequest setHTTPMethod:@"POST"];
    
    NSMutableString *postParams = [NSMutableString string];
    [postParams appendFormat:@"session=%@&", analyticsSession];
    [postParams appendFormat:@"device=%@&", device];
    [postParams appendFormat:@"system=%@&", csystem];
    [postParams appendFormat:@"version=%@&", version];
    [postParams appendFormat:@"launch=%f&", totalLaunchTime];
    
    if([Analytics_Location location].latitude && [Analytics_Location location].longitude) {
        [postParams appendFormat:@"latitude=%@&", [Analytics_Location location].latitude];
        [postParams appendFormat:@"longitude=%@&", [Analytics_Location location].longitude];
    }
    
    [urlRequest setHTTPBody:[postParams dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
    [connection start];
    

    确保您的标头方法也使用 .我的代码至少应该向您展示如何正确格式化请求,因为我可以验证这确实从我的 PHP 调用接收数据。

    【讨论】:

      猜你喜欢
      • 2014-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-24
      相关资源
      最近更新 更多