Iphone 如何将php返回的NSData转换为NSDictionary
嗨, 我正在为我的iphone应用程序创建一个登录屏幕。我使用NSURLConnection方法将用户名和密码发送到php。我可以成功地将登录详细信息发送到php。我的php页面根据登录详细信息返回状态值 (状态=正常/失败,重定向URL=) 在DidReceiveData方法中,如果我将NSData转换为字符串,则成功登录将获得以下字符串 “状态=确定&url=”。 是否有任何方法可以在不使用NSPredict的情况下获取STATUS和url的值。是否有其他方法将NSData插入NSDictionary以获取状态键的值 提前谢谢。 公羊Iphone 如何将php返回的NSData转换为NSDictionary,iphone,objective-c,nsurlconnection,Iphone,Objective C,Nsurlconnection,嗨, 我正在为我的iphone应用程序创建一个登录屏幕。我使用NSURLConnection方法将用户名和密码发送到php。我可以成功地将登录详细信息发送到php。我的php页面根据登录详细信息返回状态值 (状态=正常/失败,重定向URL=) 在DidReceiveData方法中,如果我将NSData转换为字符串,则成功登录将获得以下字符串 “状态=确定&url=”。 是否有任何方法可以在不使用NSPredict的情况下获取STATUS和url的值。是否有其他方法将NSData插入NSDicti
另一方面,NSScanner将为您提供一种更有效的方法,无论哪种方法,您都必须取消从字典中获取的任何值和键的转义。您可以使用plists的php实现,可以在这里找到 它允许您创建字符串,然后向其中添加NSDictionary,然后将字符串、数组、数据或更多字典添加到初始字典中。 您可以以xml格式或二进制格式响应plist,但是二进制更好,因为它更小,所以数据量更少。 一些谷歌搜索应该提供一些很好的例子,doco也很不错。
希望这有帮助。尝试使用此函数解析NSData,我在助手类中使用它。它使用用于iOS的JSONDecoder
NSString *urlDataString = //Whatever data was returned from the server as an NSString
NSArray *parameters = [urlDataString componentsSeparatedByString:@"&"];
NSMutableDictionary *parameterDictionary = [NSMutableDictionary dictionary];
for (NSString *parameter in parameters) {
NSArray *parameterComponents = [parameter componentsSeparatedByString:@"="];
[parameterDictionary setObject:[parameterComponents objectAtIndex:1]
forKey:[parameterComponents objectAtIndex:0]];
}
+ (NSDictionary *) JSONObjectWithData:(NSData *)data {
Class jsonSerializationClass = NSClassFromString(@"NSJSONSerialization");
if (!jsonSerializationClass) {
//iOS < 5 didn't have the JSON serialization class
JSONDecoder *parser = [[JSONDecoder alloc] init];
return [parser objectWithData:data];
}else{
NSError *error = nil;
NSDictionary *dict_response = [[NSMutableDictionary alloc] init];
dict_response = [NSJSONSerialization JSONObjectWithData:data options:NSJSONWritingPrettyPrinted error:&error];
return dict_response;
}
return nil;
}