girish_pro
girish_pro

Reputation: 848

NSMutableURLRequest remove "+" sign from request

I am developing an iOS app which required to send phone number on server. When I pass number without "+" it is work fine, but when I pass number with "+" sign (+123456, +234567) then it send number like (" 123456"," 234567").

It replace "+" by " " (space). I convert NSDictionary into JsonData .

NSError *err;
    NSData *data=[NSJSONSerialization dataWithJSONObject:mdict options:0 error:&err];
    NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSString *strjson=[NSString stringWithFormat:@"GetData=%@",str];

    NSLog(@"strjson=%@",strjson);

My code to build NSMutableRequest object.

 NSURL *url = [NSURL URLWithString:urlString];
    __weak NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[soadMessage length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:[soadMessage dataUsingEncoding:NSUTF8StringEncoding]];
    [request addValue: @"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField: @"Content-Type"];

    _connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    [_connection start];

Any help will be appreciated.

Upvotes: 0

Views: 138

Answers (2)

teamnorge
teamnorge

Reputation: 794

Try to escape your string with the CFURLCreateStringByAddingPercentEscapes

+ (NSString *)escapeValueForURLParameter:(NSString *)valueToEscape {

    if (![valueToEscape isKindOfClass:[NSString class]]) {
    valueToEscape = [(id)valueToEscape stringValue];
}

return (__bridge_transfer NSString *) CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef) valueToEscape,
                                                                              NULL, (CFStringRef) @"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8);
}

Upvotes: 1

Jose Luis
Jose Luis

Reputation: 3361

You need to format the value of mdict to take out the + character. Or you could also trim it from the JSON at the end. Either way you will get the desired result.

Something like this:

mdict["Phone"].value = [mdict["Phone"].value stringByReplacingOccurrencesOfString:@"+"
                                     withString:@""];

This is pseudocode but you get the idea. After doing this you can do the serialization and it should be fine.

Upvotes: 0

Related Questions