我知道之前已经问过,但没有一个答案能解决我的问题。这是我用来发送帖子请求的代码
NSString *nameField = _name.text;
NSString *emailField = _email.text;
NSString *usernameField = _username.text;
NSString *passwordField = _password.text;
NSURL *url = [NSURL URLWithString:@"http://localhost/api/register"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [@"name=%@&email=%@&username=%@&password=%@",nameField, emailField, usernameField, passwordField dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:@"POST"];
[request setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
这一行特意给我带来了问题
NSData *requestData = [@"name=%@&email=%@&username=%@&password=%@",nameField, emailField, usernameField, passwordField dataUsingEncoding:NSUTF8StringEncoding];
我得到的警告是
表达结果未使用
此外,我希望得到一个带有我的JSON的结果,所以当出现错误时它会显示它(后端部分已完成,它只是在iOS上显示它的问题)。我甚至不确定它是否提交
答案 0 :(得分:1)
在定义+stringWithFormat:
时忘记使用requestData
。将该行更改为:
NSData *requestData = [[NSString stringWithFormat:@"name=%@&email=%@&username=%@&password=%@", nameField, emailField, usernameField, passwordField] dataUsingEncoding:NSUTF8StringEncoding];
此外,您可能会在最后一行收到相同的警告。您可以通过将其分配给某些东西来摆脱它:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
您可能还想实现一些NSURLConnection
委托方法。有关有用的信息,请参阅this tutorial。