我的NSMutableURLRequest
将字符串发送两次到PHP。我做错了什么?
- (void)viewDidLoad {
// Printando os Dados
/////
NSString *endereco = [[NSString alloc] initWithFormat:@"%@ - CEP: %@", self.sharedData.dataEndereco, self.sharedData.dataCEP];
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:@"http://localhost/dev/mcomm/pedido.php"]];
NSLog(@"ENVI");
[request setHTTPMethod:@"POST"];
NSString *postString = [[NSString alloc] initWithFormat:@"nome=%@&email=%@&endereco=%@&produto=%@&marca=%@&preco=%@&codigo=%@&variacao=%@&parcelas=%@&valorParcelas=%@&cartao=%@&numCartao=%@&codCartao=%@&vencCartao=%@&nomeCartao=%@", self.sharedData.dataNome, self.sharedData.dataEmail, endereco, self.sharedData.dataProd, self.sharedData.dataMarca, self.sharedData.dataPreco, self.sharedData.dataCodigo, self.sharedData.dataVariacao, self.sharedData.numParcelas, self.sharedData.valorParcelas, self.sharedData.cartao, self.sharedData.numeroCartao, self.sharedData.codigoCartao, self.sharedData.dataVencimento, self.sharedData.nomeImpressoCartao];
[request setValue:[NSString
stringWithFormat:@"%d", [postString length]]
forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc]
initWithRequest:request delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[loaderAtividade startAnimating];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
答案 0 :(得分:3)
第一个请求由以下人员发起:
[[NSURLConnection alloc] initWithRequest:request delegate:self];
第二个是由函数发送的:
[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
来自apple documentation关于sendSynchronous:
的提醒重要提示:由于此调用可能需要几分钟才能失败(特别是在iOS中使用移动网络时),因此不应该从GUI应用程序的主线程中调用此函数。
您应该实现NSURLConnection委托协议并避免发送同步请求。
答案 1 :(得分:0)
除了Daniel的答案之外,你可以通过实现initWithRequest来阻止第一个请求被触发:delegate:startImmediately:with NO
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
然后,当您想要启动异步请求时,只需在连接对象上调用-start
[urlConnection start];
答案 2 :(得分:0)
NSURLConnection *conn = .....
if(conn){
......
[conn cancel];//! important!
[conn release];
}