0

我已经实现了一个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从来没有收到任何数据。可能是什么问题。任何提示或线索将不胜感激。

4

3 回答 3

4

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

查看这个相关问题的已接受答案,也可以通过 Grand Central Dispatch 完成:

dispatch_async(dispatch_get_main_queue(), ^{
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    [conn start];
});
于 2012-08-01T07:10:42.837 回答
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]];

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

于 2012-08-01T07:09:19.957 回答
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 调用接收数据。

于 2012-08-01T07:11:33.257 回答