how to convert php return NSData into NSDictionary

2019-04-15 08:30发布

HI, i am creating an login screen to my iphone application. i am sending the username and password to php using NSURLConnection method. i can successfully send login details to php. My php page returning status values based on the login details.

(status =OK / Fail , redirectionUrl=http://www.balalaa.com)

In DidReceiveData method if i convert the NSData into string i am getting following string for successful login

"STATUS=OK&url=http://www.balalaa.com".

Is there any way to fetch the values of STATUS and url, without using NSPredict. Is there any other way to conert the NSData into NSDictionary to fetch values for STATUS key?

Thanks in advance. Ram

3条回答
萌系小妹纸
2楼-- · 2019-04-15 09:03

Try this function to parse the NSData, I use it in a helper class. It uses JSONDecoder for iOS <5

+ (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;
}
查看更多
欢心
3楼-- · 2019-04-15 09:05
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]];
}

On the other hand, NSScanner will give you a much more efficient way of doing this, and either way you will have to un-escape whatever values and keys you get from the dictionary.

查看更多
成全新的幸福
4楼-- · 2019-04-15 09:06

You can use the php implementation of plists which can be found here

http://code.google.com/p/cfpropertylist/

It allows you to crete plists, you then add a NSDictionary to it and then add the strings, arrays, data or more dictionaries into the initial dictionary. You can echo the plist in either an xml format or binary, binary is better though, its smaller so less data heavy. Some googling should provide some good examples and the doco is pretty good. Hope this helps.

查看更多
登录 后发表回答