我正在尝试创建一个基本应用程序,其中包含人员详细信息并将其发布到私人服务器上。我的网址暂时保持空白,如果我使用NSURLConnectionDelegate
并使用didFailWithError
,则可以说没有连接,但是当我尝试使用NSLog
方法时,它会说
“建立连接”
出于某种原因。这是我的代码
- (void) saveData{
NSString *name = self.NameTextField.text;
NSString *phoneNumber = self.phoneNumberTextField.text;
NSString *age = self.ageTextField.text;
NSString *email = self.emailTextField.text;
//Define the URL
NSURL *url = [[NSURL alloc]initWithString:@""];
//Initialize a request from the URL
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];
//Specify that it will be a post request.
request.HTTPMethod = @"POST";
// This is how we set header fields
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
NSString *DataString = [NSString stringWithFormat:@"name=%@&phonenumber=%@&age=%@&email=%@",name,phoneNumber,age,email];
//Change your requests HTTPBody property
NSData *requestBodyData = [DataString dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
self.connection = conn;
if(self.connection){
NSLog(@"Connection is made");
}else{
NSLog(@"Connection is not made");
}
[self.connection start];
}
如果我的代码中有任何其他错误,请告知。
答案 0 :(得分:0)
您的代码检查self.connection变量是否为空,但由于alloc init似乎已成功执行,因此它不是。即对象已创建,这就是您正在检查的对象,无论它是否与您想要的是不同的故事。
答案 1 :(得分:0)
if (self.connection)
正在做的就是检查nil
是否[self.connection start];
实际上没有检查是否已在if (self.connection) {
NSLog(@"Connection is made");
} else {
NSLog(@"Connection is not made");
}
处建立连接。基本上是这样的:
if (self.connection != nil) {
NSLog(@"Connection is made");
} else {
NSLog(@"Connection is not made");
}
与
完全相同self.connection
并且nil
不是conn
,因为您已将NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
self.connection = conn;
分配给已初始化的HTTP Status
。这可以在您的代码下面的两行中看到。
didReceiveResponse:
如果您想检查连接是否成功,可以执行的操作检查- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
switch ([(NSHTTPURLResponse *)response statusCode]) {
case 200: {
NSLog(@"Received connection response!");
break;
}
default: {
NSLog(@"Something bad happened!");
break;
}
}
}
中的{{1}}代码(从Checking for valid IP for connection with NSURLConnection获取的代码)
{{1}}
或如果只是为了了解您是否可以实施Reachability code that Apple supplies或使用其他开源版本。