Search code examples
iosobjective-cnsxmlparser

How to encode a string with special characters that will be POSTed to a URL? Objective-C


Currently I have a string that I want to POST to a URL.

It works perfectly fine except when it encounters special characters like "&", and "?". It will not POST any data that comes after that. For example, if I have a string "I am something & something?", it will only POST "I am something". As for "?", it will be converted to '2' after it has been posted.

reason = 'What see see! Are you sure'2''

I am pretty sure that it must have something to do with encoding as I can see "I am something & something?" as it is just before I set the encoding:

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];

I have also tried the encodings below with no success:

NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSData *postData = [post dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSData *postData = [post dataUsingEncoding:NSISOLatin1StringEncoding];

Below are my codes from postData onwards:

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
    //NSLog(@"PostData: %@", postData);
    NSString *check = [[NSString alloc] initWithData:postData encoding:NSASCIIStringEncoding];
    NSLog(@"check string = %@", check);
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:strURLQueryString]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];
    NSURLResponse *response;
    NSError *err=nil;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSString *strResponse = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
     NSLog(@"Response: %@", strResponse);
     if(err!=nil) {
     NSLog(@"Error: %@", [err description]);
     }

Please assist. Your help(s) are appreciated.


Solution

  • There's probably a better answer out there somewhere, but this class extension has been working for me for awhile. I cobbled together the % escapes by looking at a few posts...

    //  NSString+URLEncoding.h
    @interface NSString (NSString_URLEncoding)
    
    - (NSString *)urlEncodeUsingEncoding:(CFStringEncoding)encoding;
    - (NSString *)urlEncode;
    
    @end
    
    //  NSString+URLEncoding.m
    @implementation NSString (NSString_URLEncoding)
    
    - (NSString *)urlEncodeUsingEncoding:(CFStringEncoding)encoding {
    
        return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                         (__bridge CFStringRef)self,
                                                                         NULL,
                                                                         CFSTR("!*'();:@&=+$,/?%#[]"),
                                                                         encoding));
    }
    
    - (NSString *)urlEncode {
    
        return [self urlEncodeUsingEncoding:kCFStringEncodingUTF8];
    }
    

    Then in somer other class to send a string...

    // SomeOtherClass.m
    
    #import "NSString+URLEncoding.h"
    
    NSString *encodedString = [@"This & this? are 'challenging' to !% encode" urlEncode];