网络连接丢失NSURLConnection

时间:2013-08-30 02:06:18

标签: php ios objective-c nsurlconnection nsurlrequest

每次尝试连接时都会打印此错误。不知道为什么它无法连接到服务器。构建一个简单的Java应用程序,它工作正常。我一直在冲浪StackOverflow几天试图解决这个问题。试过多个API和一些不正确的事情。如果您需要更多代码,或有任何进一步的问题,请告诉我。请帮忙。 :(

  

2013-08-29 21:56:55.946 panic [15054:70b]错误域名= NSURLErrorDomain   代码= -1005“网络连接丢失。”的UserInfo = 0xa779a30   {NSErrorFailingURLStringKey = http://54.221.224.251/,   NSErrorFailingURLKey = http://54.221.224.251/,   NSLocalizedDescription =网络连接丢失。,   NSUnderlyingError = 0xa611130“网络连接丢失。”}

以下是设置请求的代码:

NSString *urlPath = [NSString stringWithFormat:@"http://54.221.224.251"];
    [urlPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlPath];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSString *stringdata = [NSString stringWithFormat:@"name=%@&email=%@&phash=%@",name,email,phash];
    NSString *postData = [[NSString alloc] initWithString:stringdata];
    [postData stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    self.connection = connection;
    [connection start];

这是我的代码,它应该处理来自php服务器的响应。

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.receivedData appendData:data];
}
/*
 if there is an error occured, this method will be called by connection
 */
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

    NSLog(@"%@" , error);
}

/*
 if data is successfully received, this method will be called by connection
 */
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"WORKED!");
}

1 个答案:

答案 0 :(得分:0)

我不需要只放置&符号,而是需要像stringData一样添加它们。

NSString *stringdata = [NSString stringWithFormat:@"name=%@&email=%@&phash=%@",name,email,phash];

这解决了我的问题。