在NSURLConnection中将NSData转换为NSString = null

时间:2014-10-28 12:47:36

标签: ios objective-c nsstring nsdata

我正在向服务器发送数据并且它正在响应我的请求,并且我正在获取如下所示的网络文字... NSString* newStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];中的问题将出现在哪里responseData中有数据时,我的NSData没有响应。

我的回复信息:

{ret:0,msg:"<B>Your request has submitted</B><br/>Your request number is 123 <br/>Have a nice day.<br/>"}

我的代码:

    NSString *link = @"http://example.jsp";

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"first_name=%@&last_name=%@&phone=%@", link, nameField.text, surnameField.text, phoneField.text]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];

NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

NSLog(@"responseData: %@", responseData);

NSString* newStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

NSLog(@"Finish %@", newStr); // newStr is null!!

UIAlertView *message = [[UIAlertView alloc] initWithTitle:title
                                                  message:newStr
                                                 delegate:self
                                        cancelButtonTitle:@"OK"
                                        otherButtonTitles:nil];
[message show];

2 个答案:

答案 0 :(得分:0)

您的url变量可能已经nil,因为您的字符串(first_name=…)不是有效的网址:它甚至没有方案而且没有主机。

我敢打赌,如果你仔细观察,Xcode会显示一个警告,你的格式有三个占位符(%@)但是你传递了四个参数。您可能真正想做的事情就像是;

[NSString stringWithFormat:@"%@?first_name=%@&last_name=%@&phone=%@", link, nameField.text, surnameField.text, phoneField.text]

(请注意开头的额外%@?。)

在评论中你提到你确实收到数据(所以你的代码只是一个假人?)。如果您的通话[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]返回nil,则表示您的responseData不是UTF-8(这是一项非常壮举,我从未见过该方法失败;我确实得到了垃圾回收,但绝不是nil)。但是,您引用的部分看起来很正常:它会解码为\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n{ret:0,msg:"<B>Y

答案 1 :(得分:-1)

你分配了responseData吗? 你可以使用代表

来做到这一点
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
-(void)connectionDidFinishLoading:(NSURLConnection *)connection

并在

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
  NSString* newStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

 NSLog(@"Finish %@", newStr); // newStr is null!!

UIAlertView *message = [[UIAlertView alloc] initWithTitle:title
                                              message:newStr
                                             delegate:self
                                    cancelButtonTitle:@"OK"
                                    otherButtonTitles:nil];
[message show];
 }