我的JSON有问题,我发送了一个空值。
我认为我在PhP中的网络服务不是问题,因为我的PhP专家同事没有看到任何错误
就在我的Obj-C代码之下
dispatch_queue_t downloadQueue = dispatch_queue_create("downloader", NULL);
dispatch_async(downloadQueue, ^{
NSData *result = self.envoyerLaDemande;
dispatch_async(dispatch_get_main_queue(), ^{
id strResult=nil;
strResult = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];
NSLog(@"strResult: %@", strResult);
NSString* boolOk=[strResult objectForKey:@"result"];
NSLog(@"BoolOk: %@", boolOk);
还有PHP脚本
$data = array();
if(condition == 1)
{
$data["result"] = "ok";
}
else
{
$data["result"] = "error";
}
$data["result"] = "coucou";
}
echo json_encode($data);
andodeode envoyerLaDemande
-(NSData*)envoyerLaDemande{
NSURL *url = [NSURL URLWithString:@"http://mywebsite.com.com/App/V2/mailTo.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString* requestFields;
requestFields = [NSString stringWithFormat:@"agence=%@&", nomAgence];
request.HTTPBody = requestData;
request.HTTPMethod = @"POST";
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error == nil && response.statusCode == 200) {
} else {
}
return responseData;
}
答案 0 :(得分:0)
问题在于你正在做两个dispacth_async
。
在第一个中,您告诉操作系统"在后台执行此代码",这将开始在后台加载请求。但是,紧跟该代码后,您要告诉操作系统在主线程上执行一段代码。这段代码访问尚未设置的result
变量,因为它仍然在后台加载。
如果您坚持使用这些调度,只需将调度移回主队列即可。不过,请考虑查看NSURLConnectionDataDelegate
或至少使用NSURLConnection
上的sendAsynchronousRequest:queue:completionHandler
方法。
此代码应该适用于您当前的方案。
dispatch_queue_t downloadQueue = dispatch_queue_create("downloader", NULL);
dispatch_async(downloadQueue, ^{
NSData *result = self.envoyerLaDemande;
id strResult=nil;
strResult = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];
NSLog(@"strResult: %@", strResult);
NSString* boolOk=[strResult objectForKey:@"result"];
NSLog(@"BoolOk: %@", boolOk);
}
编辑:
不是简单地忽略error
和response
个对象,而是使用它们来诊断问题:
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error == nil && response.statusCode == 200) {
return responseData;
} else {
NSLog(@"Error. Status code: %d Error message: %@", response.statusCode, error.localizedDescription);
return nil;
}