我一直在尝试从我的ViewControllers
之一发送一个帖子请求,该请求从另一个ViewController
通过
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
无论如何,当我尝试发送post请求将变量发送到数据库时,最后两个参数值存储为0.我已经将float变量转换为NSStrings
。在通过NSLog
发送帖子请求之前,我检查了以确保值正确无误。但它仍然显示为零。当我通过具有完全相同值的Web浏览器手动输入表单时,它们将存储在数据库中。
我的帖子请求如下所示:
NSString *dateString = _date.text;
NSString *times = _time.text;
NSString *shape_illuminated = _shape.text;
NSString *orientation_illuminatedString = _orientation.text;
NSLog(@"compass is:%@%@", compassReceived, rollReceived);
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL * url = [NSURL URLWithString:@"http://example.com/mobile_app/submit.php"];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
NSString * params = [NSString stringWithFormat:@"date=%@&time=%@&shape_illuminated=%@&orientation_illuminated=%@&=compass_direction=%@&=degreehorizon=%@", dateString, times, shape_illuminated, orientation_illuminatedString, compassReceived, rollReceived];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"Response:%@ %@\n", response, error);
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"HttpReponseData = %@",text);
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Account error"
message:[NSString stringWithFormat:@"%@", dictionary]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
}];
[dataTask resume];
这些NSLog的一些值是:
罗盘是:127.0Angle:99.485866
在mysql中,我将字段设置为浮点数。
有什么想法吗?
UPADATE: 我试着对compass_direction和degreehorizon的值进行硬编码,但它仍然没有用。
更新: 我现在尝试使用以下方法正确配置url参数:
-(NSString *)urlenc:(NSString *)val
{
CFStringRef safeString =
CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)val,
NULL,
CFSTR("/%&=?$#+-~@<>|,.()[]{}^!"),
kCFStringEncodingUTF8);
return [NSString stringWithFormat:@"%@", safeString];
}
然后添加:
SString *query =
[NSString stringWithFormat:@"shape_illuminated=%@&orientation_illuminated=%@&=compass_direction=%@&=degreehorizon=%@",
[self urlenc:shape_illuminated],
[self urlenc:orientation_illuminatedString],
[self urlenc:convertedCompass],
[self urlenc:convertedRoll]];
NSLog(@"%@", query);
[urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content- type"];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[query dataUsingEncoding:NSUTF8StringEncoding]];
但这两个值仍未发送。 nslog的输出对我来说很好看。我甚至制作了一个php表格并在我的电脑上输入了相同的值,效果很好,所以我不知道这里发生了什么。