NSMutableURLRequest发送两次
问题描述:
我的NSMutableURLRequest
正在向PHP发送两次字符串。我究竟做错了什么?NSMutableURLRequest发送两次
- (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];
答
该第一请求是由启动:
[[NSURLConnection alloc] initWithRequest:request delegate:self];
,第二个是由函数发送:
[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
小心的词,从apple documentation关于sendSynchronous:
重要提示:由于此调用可能需要几分钟的时间才能失败(特别是在iOS中使用蜂窝网络时),您绝不应该从GUI应用程序的主线程中调用此函数。
您应该实现NSURLConnection委托协议并避免发送同步请求。
答
除了丹尼尔的回答,您可以阻止第一次请求从通过实施initWithRequest射击:委托:startImmediately:没有
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
后来的后来,当你想开始新的异步请求,你只需拨打-start连接对象
[urlConnection start];
答
NSURLConnection *conn = .....
if(conn){
......
[conn cancel];//! important!
[conn release];
}
上