Ios NSURLConnection响应返回nil
我使用以下代码获取JSON响应,但返回的响应为nil,即使打印的数据长度为256Ios NSURLConnection响应返回nil,ios,objective-c,nsurlconnection,Ios,Objective C,Nsurlconnection,我使用以下代码获取JSON响应,但返回的响应为nil,即使打印的数据长度为256 NSString *bodyString = [NSString stringWithFormat:@"{\"method\":\"cargo_shipped\",\"data\":{\"username\":\"%@\",\"shipment_no\":\"70088000071790\"}}",username]; NSMutableURLRequest *request = [NSMutableURLReq
NSString *bodyString = [NSString stringWithFormat:@"{\"method\":\"cargo_shipped\",\"data\":{\"username\":\"%@\",\"shipment_no\":\"70088000071790\"}}",username];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://url..."]];
NSLog(@"url %@",request);
NSData *postData = [bodyString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
[request setHTTPMethod:@"POST"];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSLog(@"above loop");
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
NSLog(@"ENTERED url loop");
if ([data length] > 0 && connectionError == nil)
{
NSLog(@"entered if loop");
[self receivedCargoShippedData:data];
NSString* cargoShippedResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonDatas = [cargoShippedResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDics = [NSJSONSerialization JSONObjectWithData:jsonDatas options:NSJSONReadingAllowFragments error:nil];
NSLog(@"Request %@",bodyString);
NSLog(@"Response %@",jsonDics);
NSLog(@"result: %lu ", (unsigned long)[data length]);
}
else if ([data length] == 0 && connectionError == nil)
{
[self emptyReply];
NSLog(@"empty %@",connectionError);
}
else if (connectionError != nil && connectionError.code == NSURLErrorTimedOut)
{
[self timedOut];
NSLog(@"empty %@",connectionError);
}
else if (connectionError != nil)
{
[self downloadError:connectionError];
NSLog(@"empty %@",connectionError);
} else {
NSLog(@"%@",@"wtf");
}
}];
NSLog(@"finished");
}
代码进入if循环,甚至响应的长度也是256。但是,当我试图得到答案时,答案仍然是零。我自己解决了这个问题:
if ([data length] > 0 && connectionError == nil)
{
NSLog(@"entered if loop");
[self receivedCargoShippedData:data];
NSString* forgotPasswordResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Request %@",bodyString);
NSLog(@"Response %@",forgotPasswordResponse);
}
你为什么不发布与你的问题相关的代码?我在这里看不到任何关于NSURLConnection的信息。使用
JSONObjectWithData:options:error:
的error
参数怎么样?你确定这是一本顶级词典吗?cargoShippedResponse
的值是多少?为什么您要选择NSData=>NSString=>NSData<代码>数据和jsonDatas
应该是相同的。$我已经发布了更新的代码cargoShippedResponse
的值是什么?那么数据
的值是什么?仅供参考,“如果循环”不是一件事。