NSURLConnection没有收到数据

时间:2012-08-01 07:06:56

标签: iphone ios nsurlconnection nsurlconnectiondelegate

我已经实现了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从未收到任何数据。可能是什么问题。任何提示或线索都会非常感激。

3 个答案:

答案 0 :(得分:4)

您需要将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];
});

答案 1 :(得分:2)

有一点可以肯定的是,在尝试发送请求之前,你应该% - 访问你的参数列表。

您可以将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]];

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

答案 2 :(得分:0)

以下是我的一个项目的示例:

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调用中接收数据。